From 2c7f60b1b2080ea65aea1fad49db95505ff1c117 Mon Sep 17 00:00:00 2001 From: Ali Date: Tue, 2 Jun 2026 18:00:16 +0200 Subject: [PATCH 1/2] Wasm, Gin, better generation --- .github/workflows/deploy.yml | 11 +- Makefile | 5 +- emigo/WasmReactive.go | 178 ++ examples/allegro-sdk/Makefile | 12 +- ...OfferPromotionPackageModificationAction.go | 74 + .../BatchOfferPublishUnpublishAction.go | 74 + ...essingStatusOfAPOSTOrPATCHRequestAction.go | 62 + .../CreateOfferBasedOnProductAction.go | 74 + .../DeleteADraftOfferAction.go | 62 + .../offer-management/EditAnOfferAction.go | 74 + ...llAvailableOfferPromotionPackagesAction.go | 62 + .../GetOfferPromotionPackagesAction.go | 62 + .../GetOffersWithMissingParametersAction.go | 62 + .../GetPromoOptionsForSellerSOffersAction.go | 62 + ...ModificationCommandDetailedResultAction.go | 62 + .../ModificationCommandSummaryAction.go | 62 + .../ModifyOfferPromotionPackagesAction.go | 74 + .../ModifyTheBuyNowPriceInAnOfferAction.go | 74 + .../PublishCommandDetailedReportAction.go | 62 + .../PublishCommandSummaryAction.go | 62 + .../DeleteOfferTranslationAction.go | 62 + .../GetOfferTranslationsAction.go | 62 + .../UpdateOfferTranslationAction.go | 74 + ...llDataOfTheParticularProductOfferAction.go | 62 + .../GetEventsAboutTheSellerSOffersAction.go | 62 + ...edDataOfTheParticularProductOfferAction.go | 62 + .../GetSellersOffersAction.go | 62 + ...icationReportOfTheParticularOfferAction.go | 62 + ...OfferPromotionPackageModificationAction.js | 248 ++- .../BatchOfferPublishUnpublishAction.js | 94 +- ...essingStatusOfAPOSTOrPATCHRequestAction.js | 8 - .../CreateOfferBasedOnProductAction.js | 360 +++- .../offer-management/EditAnOfferAction.js | 768 ++++++-- ...llAvailableOfferPromotionPackagesAction.js | 246 ++- .../GetOfferPromotionPackagesAction.js | 143 +- .../GetOffersWithMissingParametersAction.js | 93 +- .../GetPromoOptionsForSellerSOffersAction.js | 196 +- ...ModificationCommandDetailedResultAction.js | 238 ++- .../ModificationCommandSummaryAction.js | 8 - .../ModifyOfferPromotionPackagesAction.js | 281 ++- .../ModifyTheBuyNowPriceInAnOfferAction.js | 51 +- .../PublishCommandDetailedReportAction.js | 89 +- .../PublishCommandSummaryAction.js | 8 - .../offer-management/sdk/common/buildUrl.ts | 34 - .../offer-management/sdk/common/fetchx.ts | 196 -- .../offer-management/sdk/common/operators.ts | 173 -- .../offer-management/sdk/common/withPrefix.ts | 22 - .../sdk/envelopes/common/EnvelopeClass.ts | 16 - .../sdk/envelopes/flat-array/FlatArray.ts | 38 - .../generated/ResponseDto.ts | 1715 ----------------- .../generated/package.json | 14 - .../generated/sdk/common/withPrefix.ts | 22 - .../google-envelop.emi.yml | 125 -- .../google-json-style-guide/index.ts | 46 - .../offer-management/sdk/envelopes/index.ts | 2 - .../GetOfferTranslationsAction.js | 195 +- .../UpdateOfferTranslationAction.js | 152 +- .../offer-translations/sdk/common/buildUrl.ts | 34 - .../offer-translations/sdk/common/fetchx.ts | 196 -- .../sdk/common/operators.ts | 173 -- .../sdk/envelopes/common/EnvelopeClass.ts | 16 - .../sdk/envelopes/flat-array/FlatArray.ts | 38 - .../generated/ResponseDto.ts | 1715 ----------------- .../generated/package.json | 14 - .../generated/sdk/common/withPrefix.ts | 22 - .../google-envelop.emi.yml | 125 -- .../google-json-style-guide/index.ts | 46 - .../offer-translations/sdk/envelopes/index.ts | 2 - ...llDataOfTheParticularProductOfferAction.js | 579 ++++-- .../GetEventsAboutTheSellerSOffersAction.js | 49 +- ...edDataOfTheParticularProductOfferAction.js | 8 - .../GetSellersOffersAction.js | 95 +- ...icationReportOfTheParticularOfferAction.js | 201 +- .../sdk/common/buildUrl.ts | 34 - .../sdk/common/fetchx.ts | 196 -- .../sdk/common/operators.ts | 173 -- .../sdk/common/withPrefix.ts | 22 - .../sdk/envelopes/common/EnvelopeClass.ts | 16 - .../sdk/envelopes/flat-array/FlatArray.ts | 38 - .../generated/ResponseDto.ts | 1715 ----------------- .../generated/package.json | 14 - .../generated/sdk/common/withPrefix.ts | 22 - .../google-envelop.emi.yml | 125 -- .../google-json-style-guide/index.ts | 46 - .../sdk/envelopes/index.ts | 2 - ...OfferPromotionPackageModificationAction.kt | 14 +- .../BatchOfferPublishUnpublishAction.kt | 12 +- ...essingStatusOfAPOSTOrPATCHRequestAction.kt | 14 +- .../CreateOfferBasedOnProductAction.kt | 12 +- .../DeleteADraftOfferAction.kt | 12 +- .../offer-management/EditAnOfferAction.kt | 10 +- ...llAvailableOfferPromotionPackagesAction.kt | 14 +- .../GetOfferPromotionPackagesAction.kt | 12 +- .../GetOffersWithMissingParametersAction.kt | 14 +- .../GetPromoOptionsForSellerSOffersAction.kt | 12 +- ...ModificationCommandDetailedResultAction.kt | 14 +- .../ModificationCommandSummaryAction.kt | 14 +- .../ModifyOfferPromotionPackagesAction.kt | 14 +- .../ModifyTheBuyNowPriceInAnOfferAction.kt | 12 +- .../PublishCommandDetailedReportAction.kt | 10 +- .../PublishCommandSummaryAction.kt | 16 +- .../DeleteOfferTranslationAction.kt | 8 +- .../GetOfferTranslationsAction.kt | 12 +- .../UpdateOfferTranslationAction.kt | 12 +- ...llDataOfTheParticularProductOfferAction.kt | 10 +- .../GetEventsAboutTheSellerSOffersAction.kt | 16 +- ...edDataOfTheParticularProductOfferAction.kt | 12 +- .../GetSellersOffersAction.kt | 12 +- ...icationReportOfTheParticularOfferAction.kt | 14 +- ...OfferPromotionPackageModificationAction.ts | 398 ++-- .../BatchOfferPublishUnpublishAction.ts | 148 +- ...essingStatusOfAPOSTOrPATCHRequestAction.ts | 8 - .../CreateOfferBasedOnProductAction.ts | 574 ++++-- .../offer-management/EditAnOfferAction.ts | 1087 ++++++++--- ...llAvailableOfferPromotionPackagesAction.ts | 396 ++-- .../GetOfferPromotionPackagesAction.ts | 223 ++- .../GetOffersWithMissingParametersAction.ts | 143 +- .../GetPromoOptionsForSellerSOffersAction.ts | 314 ++- ...ModificationCommandDetailedResultAction.ts | 378 ++-- .../ModificationCommandSummaryAction.ts | 8 - .../ModifyOfferPromotionPackagesAction.ts | 457 +++-- .../ModifyTheBuyNowPriceInAnOfferAction.ts | 79 +- .../PublishCommandDetailedReportAction.ts | 128 +- .../PublishCommandSummaryAction.ts | 8 - .../offer-management/sdk/common/buildUrl.ts | 34 - .../offer-management/sdk/common/fetchx.ts | 196 -- .../offer-management/sdk/common/operators.ts | 173 -- .../offer-management/sdk/common/withPrefix.ts | 22 - .../sdk/envelopes/common/EnvelopeClass.ts | 16 - .../sdk/envelopes/flat-array/FlatArray.ts | 38 - .../generated/ResponseDto.ts | 1715 ----------------- .../generated/package.json | 14 - .../generated/sdk/common/withPrefix.ts | 22 - .../google-envelop.emi.yml | 125 -- .../google-json-style-guide/index.ts | 46 - .../offer-management/sdk/envelopes/index.ts | 2 - .../GetOfferTranslationsAction.ts | 297 ++- .../UpdateOfferTranslationAction.ts | 242 ++- .../offer-translations/sdk/common/buildUrl.ts | 34 - .../offer-translations/sdk/common/fetchx.ts | 196 -- .../sdk/common/operators.ts | 173 -- .../sdk/common/withPrefix.ts | 22 - .../sdk/envelopes/common/EnvelopeClass.ts | 16 - .../sdk/envelopes/flat-array/FlatArray.ts | 38 - .../generated/ResponseDto.ts | 1715 ----------------- .../generated/package.json | 14 - .../generated/sdk/common/withPrefix.ts | 22 - .../google-envelop.emi.yml | 125 -- .../google-json-style-guide/index.ts | 46 - .../offer-translations/sdk/envelopes/index.ts | 2 - ...llDataOfTheParticularProductOfferAction.ts | 939 ++++++--- .../GetEventsAboutTheSellerSOffersAction.ts | 77 +- ...edDataOfTheParticularProductOfferAction.ts | 8 - .../GetSellersOffersAction.ts | 138 +- ...icationReportOfTheParticularOfferAction.ts | 321 ++- .../sdk/common/buildUrl.ts | 34 - .../sdk/common/fetchx.ts | 196 -- .../sdk/common/operators.ts | 173 -- .../sdk/common/withPrefix.ts | 22 - .../sdk/envelopes/common/EnvelopeClass.ts | 16 - .../sdk/envelopes/flat-array/FlatArray.ts | 38 - .../generated/ResponseDto.ts | 1715 ----------------- .../generated/package.json | 14 - .../generated/sdk/common/withPrefix.ts | 22 - .../google-envelop.emi.yml | 125 -- .../google-json-style-guide/index.ts | 46 - .../sdk/envelopes/index.ts | 2 - .../docs/js/emi-javascript-web-socket.mdx | 15 +- .../browser/WebSocketWasm.js | 93 + .../browser/gen/ChatAction.js | 28 + .../browser/gen/CreateUserAction.js | 8 - .../browser/gen/DeleteUserAction.js | 8 - .../browser/gen/ListUsersAction.js | 38 +- .../browser/gen/SubstringAction.js | 8 - .../gen/sdk/common/URLSearchParamsX.js | 135 ++ .../browser/gen/sdk/common/WebSocketWasm.js | 95 + .../browser/gen/sdk/common/WebSocketX.js | 72 + .../gen/sdk/common/isPlausibleObject.js | 12 + .../browser/gen/sdk/common/operators.js | 54 +- .../browser/gen/sdk/js/is-plausible-object.js | 19 + .../browser/gen/sdk/react/useFetchx.js | 6 + .../browser/gen/sdk/react/useSse.js | 33 + .../browser/gen/sdk/react/useWebSocketX.js | 74 + examples/in-browser-server/browser/index.html | 21 + examples/in-browser-server/browser/main.js | 50 + examples/in-browser-server/cmd/server/main.go | 15 + examples/in-browser-server/cmd/wasm/main.go | 8 + examples/in-browser-server/go.mod | 1 + examples/in-browser-server/go.sum | 2 + .../in-browser-server.emi.yml | 5 + .../internal/ChatActionImpl.go | 36 + .../internal/defs/ChatAction.go | 116 ++ .../internal/defs/ChatActionGin.go | 238 +++ .../internal/defs/ChatActionWasm.go | 62 + .../js-sdk-kit/build/common/WebSocketWasm.js | 95 + .../js-sdk-kit/build/common/WebSocketX.js | 6 +- .../js-sdk-kit/src/common/WebSocketWasm.ts | 125 ++ examples/js-sdk-kit/src/common/WebSocketX.ts | 10 +- .../src/generated/WebSocketOrgEchoAction.ts | 15 +- .../generated/sdk/common/URLSearchParamsX.ts | 144 ++ .../src/generated/sdk/common/WebSocketWasm.ts | 125 ++ .../src/generated/sdk/common/WebSocketX.ts | 10 +- .../generated/sdk/common/isPlausibleObject.ts | 18 + .../generated/sdk/js/is-plausible-object.ts | 25 + .../src/generated/sdk/react/useSse.ts | 68 + .../sdk/common/URLSearchParamsX.ts | 144 ++ .../sdk/common/WebSocketWasm.ts | 125 ++ .../sdk/common/WebSocketX.ts | 103 + .../sdk/js/is-plausible-object.ts | 25 + .../sdk/react/useFetchx.ts | 10 + .../sdk/react/useSse.ts | 68 + .../sdk/react/useWebSocketX.ts | 104 + .../sdk/common/URLSearchParamsX.ts | 144 ++ .../sdk/common/WebSocketWasm.ts | 125 ++ .../sdk/common/WebSocketX.ts | 103 + .../sdk/common/isPlausibleObject.ts | 18 + .../sdk/common/withPrefix.ts | 2 +- .../sdk/js/is-plausible-object.ts | 25 + .../http-emi-react-output/sdk/react/useSse.ts | 68 + .../sdk/react/useWebSocketX.ts | 104 + .../sdk/common/URLSearchParamsX.ts | 144 ++ .../sdk/common/WebSocketWasm.ts | 125 ++ .../sdk/common/WebSocketX.ts | 103 + .../sdk/js/is-plausible-object.ts | 25 + .../sdk/react/useFetchx.ts | 10 + .../sdk/react/useSse.ts | 68 + .../sdk/react/useWebSocketX.ts | 104 + .../UserStreamAction.ts | 15 +- .../sdk/common/URLSearchParamsX.ts | 144 ++ .../sdk/common/WebSocketWasm.ts | 125 ++ .../sdk/common/WebSocketX.ts | 12 +- .../sdk/js/is-plausible-object.ts | 25 + .../sdk/react/useFetchx.ts | 10 + .../sdk/react/useSse.ts | 68 + .../sdk/react/useWebSocketX.ts | 104 + lib/golang/go-action-reactive-gin-realms.go | 50 + lib/golang/go-action-reactive-gin-render.go | 337 ++++ lib/golang/go-action-reactive-realms.go | 26 +- lib/golang/go-action-reactive-render.go | 332 +--- lib/golang/go-action-reactive-wasm-render.go | 115 ++ lib/golang/go-action-realms.go | 17 +- lib/golang/go-action-render.go | 3 +- lib/golang/go-common-flags.go | 25 + lib/golang/go-config.go | 17 +- lib/golang/go-manifest.go | 17 +- lib/golang/go-public-api.go | 18 +- lib/golang/go-query-params.go | 3 - lib/js/js-headers.go | 5 - lib/js/js-module.go | 58 +- lib/js/js-public-api.go | 11 + lib/js/js-sdk/common/WebSocketWasm.js | 95 + lib/js/js-sdk/common/WebSocketX.js | 6 +- lib/js/js-static-websocket-create.go | 13 +- lib/js/js-tags.go | 9 + lib/js/ts-sdk/common/WebSocketWasm.ts | 125 ++ lib/js/ts-sdk/common/WebSocketX.ts | 10 +- lib/kotlin/kotlin-public-api.go | 9 +- 257 files changed, 14136 insertions(+), 18265 deletions(-) create mode 100644 emigo/WasmReactive.go delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/buildUrl.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/fetchx.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/operators.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/index.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/buildUrl.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/fetchx.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/operators.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/index.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/buildUrl.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/fetchx.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/operators.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts delete mode 100644 examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/index.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/buildUrl.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/fetchx.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/operators.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/index.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/buildUrl.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/fetchx.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/operators.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/index.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/buildUrl.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/fetchx.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/operators.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts delete mode 100644 examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/index.ts create mode 100644 examples/in-browser-server/browser/WebSocketWasm.js create mode 100644 examples/in-browser-server/browser/gen/ChatAction.js create mode 100644 examples/in-browser-server/browser/gen/sdk/common/URLSearchParamsX.js create mode 100644 examples/in-browser-server/browser/gen/sdk/common/WebSocketWasm.js create mode 100644 examples/in-browser-server/browser/gen/sdk/common/WebSocketX.js create mode 100644 examples/in-browser-server/browser/gen/sdk/common/isPlausibleObject.js create mode 100644 examples/in-browser-server/browser/gen/sdk/js/is-plausible-object.js create mode 100644 examples/in-browser-server/browser/gen/sdk/react/useFetchx.js create mode 100644 examples/in-browser-server/browser/gen/sdk/react/useSse.js create mode 100644 examples/in-browser-server/browser/gen/sdk/react/useWebSocketX.js create mode 100644 examples/in-browser-server/internal/ChatActionImpl.go create mode 100644 examples/in-browser-server/internal/defs/ChatAction.go create mode 100644 examples/in-browser-server/internal/defs/ChatActionGin.go create mode 100644 examples/in-browser-server/internal/defs/ChatActionWasm.go create mode 100644 examples/js-sdk-kit/build/common/WebSocketWasm.js create mode 100644 examples/js-sdk-kit/src/common/WebSocketWasm.ts create mode 100644 examples/js-test/reactclient/src/generated/sdk/common/URLSearchParamsX.ts create mode 100644 examples/js-test/reactclient/src/generated/sdk/common/WebSocketWasm.ts create mode 100644 examples/js-test/reactclient/src/generated/sdk/common/isPlausibleObject.ts create mode 100644 examples/js-test/reactclient/src/generated/sdk/js/is-plausible-object.ts create mode 100644 examples/js-test/reactclient/src/generated/sdk/react/useSse.ts create mode 100644 examples/js/test-artifacts/http-action-test-output/sdk/common/URLSearchParamsX.ts create mode 100644 examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketWasm.ts create mode 100644 examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketX.ts create mode 100644 examples/js/test-artifacts/http-action-test-output/sdk/js/is-plausible-object.ts create mode 100644 examples/js/test-artifacts/http-action-test-output/sdk/react/useFetchx.ts create mode 100644 examples/js/test-artifacts/http-action-test-output/sdk/react/useSse.ts create mode 100644 examples/js/test-artifacts/http-action-test-output/sdk/react/useWebSocketX.ts create mode 100644 examples/js/test-artifacts/http-emi-react-output/sdk/common/URLSearchParamsX.ts create mode 100644 examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketWasm.ts create mode 100644 examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketX.ts create mode 100644 examples/js/test-artifacts/http-emi-react-output/sdk/common/isPlausibleObject.ts rename examples/{allegro-sdk/javascript/gen/offer/offer-translations => js/test-artifacts/http-emi-react-output}/sdk/common/withPrefix.ts (97%) create mode 100644 examples/js/test-artifacts/http-emi-react-output/sdk/js/is-plausible-object.ts create mode 100644 examples/js/test-artifacts/http-emi-react-output/sdk/react/useSse.ts create mode 100644 examples/js/test-artifacts/http-emi-react-output/sdk/react/useWebSocketX.ts create mode 100644 examples/js/test-artifacts/http-envelop-test-output/sdk/common/URLSearchParamsX.ts create mode 100644 examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketWasm.ts create mode 100644 examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketX.ts create mode 100644 examples/js/test-artifacts/http-envelop-test-output/sdk/js/is-plausible-object.ts create mode 100644 examples/js/test-artifacts/http-envelop-test-output/sdk/react/useFetchx.ts create mode 100644 examples/js/test-artifacts/http-envelop-test-output/sdk/react/useSse.ts create mode 100644 examples/js/test-artifacts/http-envelop-test-output/sdk/react/useWebSocketX.ts create mode 100644 examples/js/test-artifacts/web-socket-test-output/sdk/common/URLSearchParamsX.ts create mode 100644 examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketWasm.ts create mode 100644 examples/js/test-artifacts/web-socket-test-output/sdk/js/is-plausible-object.ts create mode 100644 examples/js/test-artifacts/web-socket-test-output/sdk/react/useFetchx.ts create mode 100644 examples/js/test-artifacts/web-socket-test-output/sdk/react/useSse.ts create mode 100644 examples/js/test-artifacts/web-socket-test-output/sdk/react/useWebSocketX.ts create mode 100644 lib/golang/go-action-reactive-gin-realms.go create mode 100644 lib/golang/go-action-reactive-gin-render.go create mode 100644 lib/golang/go-action-reactive-wasm-render.go create mode 100644 lib/golang/go-common-flags.go create mode 100644 lib/js/js-sdk/common/WebSocketWasm.js create mode 100644 lib/js/js-tags.go create mode 100644 lib/js/ts-sdk/common/WebSocketWasm.ts diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index e32ce6cd..f7cdf92a 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -39,6 +39,9 @@ jobs: - name: Make standard binary file run: make unix + + - name: Make it globally available + run: sudo cp ./emi /usr/local/bin/emi && sudo chmod +x /usr/local/bin/emi - name: Build Playground run: cd playground && npm run build @@ -48,7 +51,8 @@ jobs: - name: Javascript tests run: cd ./examples/js && npm i -f && npx vitest run - + + - name: The the virtual ecosystem run: cd ./examples/virtual-eco-system && make build @@ -56,6 +60,11 @@ jobs: - name: Compile the web veresion (docs, and only after running tests because they create document) run: cd ./examples/emi-web && npm i -f && npm run build + - name: Regenerate allegro + run: cd ./examples/allegro-sdk && make + + - name: Check swift + run: make check_swift - name: Add web version and playground into same run: make compile-github diff --git a/Makefile b/Makefile index 7294e6f4..92ed9d0c 100644 --- a/Makefile +++ b/Makefile @@ -73,4 +73,7 @@ collectiontest: test_examples: - cd examples/fullstack && make \ No newline at end of file + cd examples/fullstack && make + +check_swift: + cd examples/allegro-sdk/swift && find . -type f -name "*.swift" -print0 | xargs -0 swiftc -typecheck \ No newline at end of file diff --git a/emigo/WasmReactive.go b/emigo/WasmReactive.go new file mode 100644 index 00000000..79f09eb5 --- /dev/null +++ b/emigo/WasmReactive.go @@ -0,0 +1,178 @@ +//go:build wasm + +package emigo + +import ( + "net/url" + "sync" + "sync/atomic" + "syscall/js" +) + +// WasmReactiveConn is the server-side view of one logical client connection. +// It is the websocket-conn analogue for the browser: there is no socket, just +// two channels bridged to JS callbacks. +// +// Read carries client -> server frames (fed by wasmWsSend) +// Write carries server -> client frames (drained into the onMessage callback) +// Done fires once when either side tears the connection down +// +// This mirrors the channel contract of the gorilla-backed reactive session, so +// the same developer factory can drive either transport. +type WasmReactiveConn struct { + Read chan []byte + Write chan []byte + Done chan bool + Query url.Values +} + +// WasmReactiveHandler sets up one connection. It runs once per WebSocketWasm the +// browser opens. Wire your read/write loops against conn here; return an error +// to reject the connection (the error text is delivered as one final message). +type WasmReactiveHandler func(conn *WasmReactiveConn) error + +// WasmReactor is the reactive counterpart of LiftWasmServer. Where LiftWasmServer +// turns a single JS call into one HTTP request/response, the reactor manages +// long-lived connections and exposes three JS entry points the WebSocketWasm +// class drives: +// +// wasmWsOpen(path, query, onMessage, onClose) -> connId | -1 +// wasmWsSend(connId, data) -> bool +// wasmWsClose(connId) -> bool +// +// The reactive path deliberately bypasses net/http: gorilla's Upgrade needs to +// hijack a real net.Conn, which the in-browser httptest server has no notion of. +// Talking channels straight to JS sidesteps the handshake and framing entirely. +type WasmReactor struct { + mu sync.Mutex + handlers map[string]WasmReactiveHandler + conns map[int]*WasmReactiveConn + nextID int64 +} + +func NewWasmReactor() *WasmReactor { + return &WasmReactor{ + handlers: map[string]WasmReactiveHandler{}, + conns: map[int]*WasmReactiveConn{}, + } +} + +// Handle registers a reactive handler under a path. The browser selects it via +// the pathname of the URL passed to new WebSocketWasm(url). +func (r *WasmReactor) Handle(path string, h WasmReactiveHandler) { + r.mu.Lock() + r.handlers[path] = h + r.mu.Unlock() +} + +// Lift exposes the JS entry points. Call it once, after registering handlers. +func (r *WasmReactor) Lift() { + js.Global().Set("wasmWsOpen", js.FuncOf(r.jsOpen)) + js.Global().Set("wasmWsSend", js.FuncOf(r.jsSend)) + js.Global().Set("wasmWsClose", js.FuncOf(r.jsClose)) +} + +func (r *WasmReactor) drop(id int) { + r.mu.Lock() + delete(r.conns, id) + r.mu.Unlock() +} + +// jsOpen: wasmWsOpen(path, query, onMessage, onClose) -> connId | -1 +func (r *WasmReactor) jsOpen(_ js.Value, a []js.Value) any { + path := a[0].String() + rawQuery := a[1].String() + onMessage := a[2] // function(dataString) + onClose := a[3] // function(reasonString) + + r.mu.Lock() + h, ok := r.handlers[path] + r.mu.Unlock() + if !ok { + return -1 + } + + q, _ := url.ParseQuery(rawQuery) + conn := &WasmReactiveConn{ + Read: make(chan []byte, 16), + Write: make(chan []byte, 16), + Done: make(chan bool, 1), + Query: q, + } + id := int(atomic.AddInt64(&r.nextID, 1)) + r.mu.Lock() + r.conns[id] = conn + r.mu.Unlock() + + // server -> client pump. Exactly one onClose fires: whichever of Write-close + // or Done lands first wins, then the goroutine returns. + go func() { + for { + select { + case msg, ok := <-conn.Write: + if !ok { + onClose.Invoke("server closed") + r.drop(id) + return + } + onMessage.Invoke(string(msg)) + case <-conn.Done: + onClose.Invoke("closed") + r.drop(id) + return + } + } + }() + + // Run the developer handler. On setup error, deliver the text and tear down. + go func() { + if err := h(conn); err != nil { + onMessage.Invoke("error: " + err.Error()) + select { + case conn.Done <- true: + default: + } + } + }() + + return id +} + +// jsSend: wasmWsSend(connId, data) -> bool +func (r *WasmReactor) jsSend(_ js.Value, a []js.Value) any { + id := a[0].Int() + data := a[1].String() + + r.mu.Lock() + conn := r.conns[id] + r.mu.Unlock() + if conn == nil { + return false + } + // Feed the frame on a goroutine: a synchronous JS->Go call must not block + // the event loop waiting on a busy handler. + go func() { + select { + case conn.Read <- []byte(data): + case <-conn.Done: + } + }() + return true +} + +// jsClose: wasmWsClose(connId) -> bool +func (r *WasmReactor) jsClose(_ js.Value, a []js.Value) any { + id := a[0].Int() + + r.mu.Lock() + conn := r.conns[id] + r.mu.Unlock() + if conn == nil { + return false + } + select { + case conn.Done <- true: + default: + } + return true +} diff --git a/examples/allegro-sdk/Makefile b/examples/allegro-sdk/Makefile index f6933e55..69ba4415 100644 --- a/examples/allegro-sdk/Makefile +++ b/examples/allegro-sdk/Makefile @@ -3,15 +3,15 @@ gen: gen-js: rm -rf javascript/gen/ && \ - emi js --path definitions/offer/user-offer-information.emi.yml --output javascript/gen/offer/user-offer-information && \ - emi js --path definitions/offer/offer-translations.emi.yml --output javascript/gen/offer/offer-translations && \ - emi js --path definitions/offer/offer-management.emi.yml --output javascript/gen/offer/offer-management + emi js --tags no-sdk --path definitions/offer/user-offer-information.emi.yml --output javascript/gen/offer/user-offer-information && \ + emi js --tags no-sdk --path definitions/offer/offer-translations.emi.yml --output javascript/gen/offer/offer-translations && \ + emi js --tags no-sdk --path definitions/offer/offer-management.emi.yml --output javascript/gen/offer/offer-management gen-ts: rm -rf typescript/gen/ && \ - emi js --path definitions/offer/user-offer-information.emi.yml --output typescript/gen/offer/user-offer-information --tags typescript && \ - emi js --path definitions/offer/offer-translations.emi.yml --output typescript/gen/offer/offer-translations --tags typescript && \ - emi js --path definitions/offer/offer-management.emi.yml --output typescript/gen/offer/offer-management --tags typescript + emi js --path definitions/offer/user-offer-information.emi.yml --output typescript/gen/offer/user-offer-information --tags typescript,no-sdk && \ + emi js --path definitions/offer/offer-translations.emi.yml --output typescript/gen/offer/offer-translations --tags typescript,no-sdk && \ + emi js --path definitions/offer/offer-management.emi.yml --output typescript/gen/offer/offer-management --tags typescript,no-sdk gen-kotlin: rm -rf kotlin/gen/ && \ diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.go index 8c0f07d4..61b81d56 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.go @@ -621,3 +621,77 @@ func (x BatchOfferPromotionPackageModificationActionRequest) IsCli() bool { } return true } + +// BatchOfferPromotionPackageModificationActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the BatchOfferPromotionPackageModificationAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *BatchOfferPromotionPackageModificationActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func BatchOfferPromotionPackageModificationActionHttpHandler( + handler func(c BatchOfferPromotionPackageModificationActionRequest) (*BatchOfferPromotionPackageModificationActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := BatchOfferPromotionPackageModificationActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + var body BatchOfferPromotionPackageModificationActionReq + if r.Body != nil { + defer r.Body.Close() + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + if err := json.Unmarshal(data, &body); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + } + } + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := BatchOfferPromotionPackageModificationActionRequest{ + Body: body, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// BatchOfferPromotionPackageModificationActionHttp is a high-level convenience wrapper around +// BatchOfferPromotionPackageModificationActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func BatchOfferPromotionPackageModificationActionHttp( + mux *http.ServeMux, + handler func(c BatchOfferPromotionPackageModificationActionRequest) (*BatchOfferPromotionPackageModificationActionResponse, error), +) { + method, pattern, h := BatchOfferPromotionPackageModificationActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPublishUnpublishAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPublishUnpublishAction.go index 5376059d..84d7daa9 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPublishUnpublishAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/BatchOfferPublishUnpublishAction.go @@ -468,3 +468,77 @@ func (x BatchOfferPublishUnpublishActionRequest) IsCli() bool { } return true } + +// BatchOfferPublishUnpublishActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the BatchOfferPublishUnpublishAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *BatchOfferPublishUnpublishActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func BatchOfferPublishUnpublishActionHttpHandler( + handler func(c BatchOfferPublishUnpublishActionRequest) (*BatchOfferPublishUnpublishActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := BatchOfferPublishUnpublishActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + var body BatchOfferPublishUnpublishActionReq + if r.Body != nil { + defer r.Body.Close() + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + if err := json.Unmarshal(data, &body); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + } + } + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := BatchOfferPublishUnpublishActionRequest{ + Body: body, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// BatchOfferPublishUnpublishActionHttp is a high-level convenience wrapper around +// BatchOfferPublishUnpublishActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func BatchOfferPublishUnpublishActionHttp( + mux *http.ServeMux, + handler func(c BatchOfferPublishUnpublishActionRequest) (*BatchOfferPublishUnpublishActionResponse, error), +) { + method, pattern, h := BatchOfferPublishUnpublishActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.go index 60b22d7c..0446531c 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.go @@ -353,3 +353,65 @@ func (x CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionRequest) IsCli() bool } return true } + +// CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionHttpHandler( + handler func(c CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionRequest) (*CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionHttp is a high-level convenience wrapper around +// CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionHttp( + mux *http.ServeMux, + handler func(c CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionRequest) (*CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionResponse, error), +) { + method, pattern, h := CheckTheProcessingStatusOfAPOSTOrPATCHRequestActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/CreateOfferBasedOnProductAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/CreateOfferBasedOnProductAction.go index 8cac8b5a..8bbe6f5c 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/CreateOfferBasedOnProductAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/CreateOfferBasedOnProductAction.go @@ -1815,3 +1815,77 @@ func (x CreateOfferBasedOnProductActionRequest) IsCli() bool { } return true } + +// CreateOfferBasedOnProductActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the CreateOfferBasedOnProductAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *CreateOfferBasedOnProductActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func CreateOfferBasedOnProductActionHttpHandler( + handler func(c CreateOfferBasedOnProductActionRequest) (*CreateOfferBasedOnProductActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := CreateOfferBasedOnProductActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + var body CreateOfferBasedOnProductActionReq + if r.Body != nil { + defer r.Body.Close() + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + if err := json.Unmarshal(data, &body); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + } + } + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := CreateOfferBasedOnProductActionRequest{ + Body: body, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// CreateOfferBasedOnProductActionHttp is a high-level convenience wrapper around +// CreateOfferBasedOnProductActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func CreateOfferBasedOnProductActionHttp( + mux *http.ServeMux, + handler func(c CreateOfferBasedOnProductActionRequest) (*CreateOfferBasedOnProductActionResponse, error), +) { + method, pattern, h := CreateOfferBasedOnProductActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/DeleteADraftOfferAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/DeleteADraftOfferAction.go index 4e6cdfbe..d279d6cc 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/DeleteADraftOfferAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/DeleteADraftOfferAction.go @@ -250,3 +250,65 @@ func (x DeleteADraftOfferActionRequest) IsCli() bool { } return true } + +// DeleteADraftOfferActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the DeleteADraftOfferAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *DeleteADraftOfferActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func DeleteADraftOfferActionHttpHandler( + handler func(c DeleteADraftOfferActionRequest) (*DeleteADraftOfferActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := DeleteADraftOfferActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := DeleteADraftOfferActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// DeleteADraftOfferActionHttp is a high-level convenience wrapper around +// DeleteADraftOfferActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func DeleteADraftOfferActionHttp( + mux *http.ServeMux, + handler func(c DeleteADraftOfferActionRequest) (*DeleteADraftOfferActionResponse, error), +) { + method, pattern, h := DeleteADraftOfferActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/EditAnOfferAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/EditAnOfferAction.go index 6e76b81d..5b5156e7 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/EditAnOfferAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/EditAnOfferAction.go @@ -3742,3 +3742,77 @@ func (x EditAnOfferActionRequest) IsCli() bool { } return true } + +// EditAnOfferActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the EditAnOfferAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *EditAnOfferActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func EditAnOfferActionHttpHandler( + handler func(c EditAnOfferActionRequest) (*EditAnOfferActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := EditAnOfferActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + var body EditAnOfferActionReq + if r.Body != nil { + defer r.Body.Close() + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + if err := json.Unmarshal(data, &body); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + } + } + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := EditAnOfferActionRequest{ + Body: body, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// EditAnOfferActionHttp is a high-level convenience wrapper around +// EditAnOfferActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func EditAnOfferActionHttp( + mux *http.ServeMux, + handler func(c EditAnOfferActionRequest) (*EditAnOfferActionResponse, error), +) { + method, pattern, h := EditAnOfferActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.go index 5aefdafe..b664243e 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.go @@ -494,3 +494,65 @@ func (x GetAllAvailableOfferPromotionPackagesActionRequest) IsCli() bool { } return true } + +// GetAllAvailableOfferPromotionPackagesActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetAllAvailableOfferPromotionPackagesAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetAllAvailableOfferPromotionPackagesActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetAllAvailableOfferPromotionPackagesActionHttpHandler( + handler func(c GetAllAvailableOfferPromotionPackagesActionRequest) (*GetAllAvailableOfferPromotionPackagesActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetAllAvailableOfferPromotionPackagesActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetAllAvailableOfferPromotionPackagesActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetAllAvailableOfferPromotionPackagesActionHttp is a high-level convenience wrapper around +// GetAllAvailableOfferPromotionPackagesActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetAllAvailableOfferPromotionPackagesActionHttp( + mux *http.ServeMux, + handler func(c GetAllAvailableOfferPromotionPackagesActionRequest) (*GetAllAvailableOfferPromotionPackagesActionResponse, error), +) { + method, pattern, h := GetAllAvailableOfferPromotionPackagesActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/GetOfferPromotionPackagesAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/GetOfferPromotionPackagesAction.go index d7216fc6..8f646164 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/GetOfferPromotionPackagesAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/GetOfferPromotionPackagesAction.go @@ -688,3 +688,65 @@ func (x GetOfferPromotionPackagesActionRequest) IsCli() bool { } return true } + +// GetOfferPromotionPackagesActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetOfferPromotionPackagesAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetOfferPromotionPackagesActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetOfferPromotionPackagesActionHttpHandler( + handler func(c GetOfferPromotionPackagesActionRequest) (*GetOfferPromotionPackagesActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetOfferPromotionPackagesActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetOfferPromotionPackagesActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetOfferPromotionPackagesActionHttp is a high-level convenience wrapper around +// GetOfferPromotionPackagesActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetOfferPromotionPackagesActionHttp( + mux *http.ServeMux, + handler func(c GetOfferPromotionPackagesActionRequest) (*GetOfferPromotionPackagesActionResponse, error), +) { + method, pattern, h := GetOfferPromotionPackagesActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/GetOffersWithMissingParametersAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/GetOffersWithMissingParametersAction.go index d7519c6f..2c04783f 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/GetOffersWithMissingParametersAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/GetOffersWithMissingParametersAction.go @@ -381,3 +381,65 @@ func (x GetOffersWithMissingParametersActionRequest) IsCli() bool { } return true } + +// GetOffersWithMissingParametersActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetOffersWithMissingParametersAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetOffersWithMissingParametersActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetOffersWithMissingParametersActionHttpHandler( + handler func(c GetOffersWithMissingParametersActionRequest) (*GetOffersWithMissingParametersActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetOffersWithMissingParametersActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetOffersWithMissingParametersActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetOffersWithMissingParametersActionHttp is a high-level convenience wrapper around +// GetOffersWithMissingParametersActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetOffersWithMissingParametersActionHttp( + mux *http.ServeMux, + handler func(c GetOffersWithMissingParametersActionRequest) (*GetOffersWithMissingParametersActionResponse, error), +) { + method, pattern, h := GetOffersWithMissingParametersActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.go index 1363ad75..aa46a3e4 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.go @@ -725,3 +725,65 @@ func (x GetPromoOptionsForSellerSOffersActionRequest) IsCli() bool { } return true } + +// GetPromoOptionsForSellerSOffersActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetPromoOptionsForSellerSOffersAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetPromoOptionsForSellerSOffersActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetPromoOptionsForSellerSOffersActionHttpHandler( + handler func(c GetPromoOptionsForSellerSOffersActionRequest) (*GetPromoOptionsForSellerSOffersActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetPromoOptionsForSellerSOffersActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetPromoOptionsForSellerSOffersActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetPromoOptionsForSellerSOffersActionHttp is a high-level convenience wrapper around +// GetPromoOptionsForSellerSOffersActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetPromoOptionsForSellerSOffersActionHttp( + mux *http.ServeMux, + handler func(c GetPromoOptionsForSellerSOffersActionRequest) (*GetPromoOptionsForSellerSOffersActionResponse, error), +) { + method, pattern, h := GetPromoOptionsForSellerSOffersActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandDetailedResultAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandDetailedResultAction.go index fa20b25e..a4b7e833 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandDetailedResultAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandDetailedResultAction.go @@ -658,3 +658,65 @@ func (x ModificationCommandDetailedResultActionRequest) IsCli() bool { } return true } + +// ModificationCommandDetailedResultActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the ModificationCommandDetailedResultAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *ModificationCommandDetailedResultActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func ModificationCommandDetailedResultActionHttpHandler( + handler func(c ModificationCommandDetailedResultActionRequest) (*ModificationCommandDetailedResultActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := ModificationCommandDetailedResultActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := ModificationCommandDetailedResultActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// ModificationCommandDetailedResultActionHttp is a high-level convenience wrapper around +// ModificationCommandDetailedResultActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func ModificationCommandDetailedResultActionHttp( + mux *http.ServeMux, + handler func(c ModificationCommandDetailedResultActionRequest) (*ModificationCommandDetailedResultActionResponse, error), +) { + method, pattern, h := ModificationCommandDetailedResultActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandSummaryAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandSummaryAction.go index 36d1b041..1d3dde28 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandSummaryAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/ModificationCommandSummaryAction.go @@ -331,3 +331,65 @@ func (x ModificationCommandSummaryActionRequest) IsCli() bool { } return true } + +// ModificationCommandSummaryActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the ModificationCommandSummaryAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *ModificationCommandSummaryActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func ModificationCommandSummaryActionHttpHandler( + handler func(c ModificationCommandSummaryActionRequest) (*ModificationCommandSummaryActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := ModificationCommandSummaryActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := ModificationCommandSummaryActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// ModificationCommandSummaryActionHttp is a high-level convenience wrapper around +// ModificationCommandSummaryActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func ModificationCommandSummaryActionHttp( + mux *http.ServeMux, + handler func(c ModificationCommandSummaryActionRequest) (*ModificationCommandSummaryActionResponse, error), +) { + method, pattern, h := ModificationCommandSummaryActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.go index 32fc9baf..ed727af3 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.go @@ -832,3 +832,77 @@ func (x ModifyOfferPromotionPackagesActionRequest) IsCli() bool { } return true } + +// ModifyOfferPromotionPackagesActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the ModifyOfferPromotionPackagesAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *ModifyOfferPromotionPackagesActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func ModifyOfferPromotionPackagesActionHttpHandler( + handler func(c ModifyOfferPromotionPackagesActionRequest) (*ModifyOfferPromotionPackagesActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := ModifyOfferPromotionPackagesActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + var body ModifyOfferPromotionPackagesActionReq + if r.Body != nil { + defer r.Body.Close() + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + if err := json.Unmarshal(data, &body); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + } + } + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := ModifyOfferPromotionPackagesActionRequest{ + Body: body, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// ModifyOfferPromotionPackagesActionHttp is a high-level convenience wrapper around +// ModifyOfferPromotionPackagesActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func ModifyOfferPromotionPackagesActionHttp( + mux *http.ServeMux, + handler func(c ModifyOfferPromotionPackagesActionRequest) (*ModifyOfferPromotionPackagesActionResponse, error), +) { + method, pattern, h := ModifyOfferPromotionPackagesActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.go index 2efa23a9..86b094fd 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.go @@ -559,3 +559,77 @@ func (x ModifyTheBuyNowPriceInAnOfferActionRequest) IsCli() bool { } return true } + +// ModifyTheBuyNowPriceInAnOfferActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the ModifyTheBuyNowPriceInAnOfferAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *ModifyTheBuyNowPriceInAnOfferActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func ModifyTheBuyNowPriceInAnOfferActionHttpHandler( + handler func(c ModifyTheBuyNowPriceInAnOfferActionRequest) (*ModifyTheBuyNowPriceInAnOfferActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := ModifyTheBuyNowPriceInAnOfferActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + var body ModifyTheBuyNowPriceInAnOfferActionReq + if r.Body != nil { + defer r.Body.Close() + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + if err := json.Unmarshal(data, &body); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + } + } + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := ModifyTheBuyNowPriceInAnOfferActionRequest{ + Body: body, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// ModifyTheBuyNowPriceInAnOfferActionHttp is a high-level convenience wrapper around +// ModifyTheBuyNowPriceInAnOfferActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func ModifyTheBuyNowPriceInAnOfferActionHttp( + mux *http.ServeMux, + handler func(c ModifyTheBuyNowPriceInAnOfferActionRequest) (*ModifyTheBuyNowPriceInAnOfferActionResponse, error), +) { + method, pattern, h := ModifyTheBuyNowPriceInAnOfferActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandDetailedReportAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandDetailedReportAction.go index 954a65aa..8497d537 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandDetailedReportAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandDetailedReportAction.go @@ -443,3 +443,65 @@ func (x PublishCommandDetailedReportActionRequest) IsCli() bool { } return true } + +// PublishCommandDetailedReportActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the PublishCommandDetailedReportAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *PublishCommandDetailedReportActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func PublishCommandDetailedReportActionHttpHandler( + handler func(c PublishCommandDetailedReportActionRequest) (*PublishCommandDetailedReportActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := PublishCommandDetailedReportActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := PublishCommandDetailedReportActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// PublishCommandDetailedReportActionHttp is a high-level convenience wrapper around +// PublishCommandDetailedReportActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func PublishCommandDetailedReportActionHttp( + mux *http.ServeMux, + handler func(c PublishCommandDetailedReportActionRequest) (*PublishCommandDetailedReportActionResponse, error), +) { + method, pattern, h := PublishCommandDetailedReportActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandSummaryAction.go b/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandSummaryAction.go index ccec5c10..7f7a3f48 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandSummaryAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-management/PublishCommandSummaryAction.go @@ -347,3 +347,65 @@ func (x PublishCommandSummaryActionRequest) IsCli() bool { } return true } + +// PublishCommandSummaryActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the PublishCommandSummaryAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *PublishCommandSummaryActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func PublishCommandSummaryActionHttpHandler( + handler func(c PublishCommandSummaryActionRequest) (*PublishCommandSummaryActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := PublishCommandSummaryActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := PublishCommandSummaryActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// PublishCommandSummaryActionHttp is a high-level convenience wrapper around +// PublishCommandSummaryActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func PublishCommandSummaryActionHttp( + mux *http.ServeMux, + handler func(c PublishCommandSummaryActionRequest) (*PublishCommandSummaryActionResponse, error), +) { + method, pattern, h := PublishCommandSummaryActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-translations/DeleteOfferTranslationAction.go b/examples/allegro-sdk/golang/gen/offer/offer-translations/DeleteOfferTranslationAction.go index c0cbe627..39368dfb 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-translations/DeleteOfferTranslationAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-translations/DeleteOfferTranslationAction.go @@ -250,3 +250,65 @@ func (x DeleteOfferTranslationActionRequest) IsCli() bool { } return true } + +// DeleteOfferTranslationActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the DeleteOfferTranslationAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *DeleteOfferTranslationActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func DeleteOfferTranslationActionHttpHandler( + handler func(c DeleteOfferTranslationActionRequest) (*DeleteOfferTranslationActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := DeleteOfferTranslationActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := DeleteOfferTranslationActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// DeleteOfferTranslationActionHttp is a high-level convenience wrapper around +// DeleteOfferTranslationActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func DeleteOfferTranslationActionHttp( + mux *http.ServeMux, + handler func(c DeleteOfferTranslationActionRequest) (*DeleteOfferTranslationActionResponse, error), +) { + method, pattern, h := DeleteOfferTranslationActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-translations/GetOfferTranslationsAction.go b/examples/allegro-sdk/golang/gen/offer/offer-translations/GetOfferTranslationsAction.go index 01f576d4..8481bde0 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-translations/GetOfferTranslationsAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-translations/GetOfferTranslationsAction.go @@ -513,3 +513,65 @@ func (x GetOfferTranslationsActionRequest) IsCli() bool { } return true } + +// GetOfferTranslationsActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetOfferTranslationsAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetOfferTranslationsActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetOfferTranslationsActionHttpHandler( + handler func(c GetOfferTranslationsActionRequest) (*GetOfferTranslationsActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetOfferTranslationsActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetOfferTranslationsActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetOfferTranslationsActionHttp is a high-level convenience wrapper around +// GetOfferTranslationsActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetOfferTranslationsActionHttp( + mux *http.ServeMux, + handler func(c GetOfferTranslationsActionRequest) (*GetOfferTranslationsActionResponse, error), +) { + method, pattern, h := GetOfferTranslationsActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/offer-translations/UpdateOfferTranslationAction.go b/examples/allegro-sdk/golang/gen/offer/offer-translations/UpdateOfferTranslationAction.go index e4174c66..cbfea907 100644 --- a/examples/allegro-sdk/golang/gen/offer/offer-translations/UpdateOfferTranslationAction.go +++ b/examples/allegro-sdk/golang/gen/offer/offer-translations/UpdateOfferTranslationAction.go @@ -458,3 +458,77 @@ func (x UpdateOfferTranslationActionRequest) IsCli() bool { } return true } + +// UpdateOfferTranslationActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the UpdateOfferTranslationAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *UpdateOfferTranslationActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func UpdateOfferTranslationActionHttpHandler( + handler func(c UpdateOfferTranslationActionRequest) (*UpdateOfferTranslationActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := UpdateOfferTranslationActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + var body UpdateOfferTranslationActionReq + if r.Body != nil { + defer r.Body.Close() + if data, _ := io.ReadAll(r.Body); len(data) > 0 { + if err := json.Unmarshal(data, &body); err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + } + } + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := UpdateOfferTranslationActionRequest{ + Body: body, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// UpdateOfferTranslationActionHttp is a high-level convenience wrapper around +// UpdateOfferTranslationActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func UpdateOfferTranslationActionHttp( + mux *http.ServeMux, + handler func(c UpdateOfferTranslationActionRequest) (*UpdateOfferTranslationActionResponse, error), +) { + method, pattern, h := UpdateOfferTranslationActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.go b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.go index 44445eec..8e56d236 100644 --- a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.go +++ b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.go @@ -1989,3 +1989,65 @@ func (x GetAllDataOfTheParticularProductOfferActionRequest) IsCli() bool { } return true } + +// GetAllDataOfTheParticularProductOfferActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetAllDataOfTheParticularProductOfferAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetAllDataOfTheParticularProductOfferActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetAllDataOfTheParticularProductOfferActionHttpHandler( + handler func(c GetAllDataOfTheParticularProductOfferActionRequest) (*GetAllDataOfTheParticularProductOfferActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetAllDataOfTheParticularProductOfferActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetAllDataOfTheParticularProductOfferActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetAllDataOfTheParticularProductOfferActionHttp is a high-level convenience wrapper around +// GetAllDataOfTheParticularProductOfferActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetAllDataOfTheParticularProductOfferActionHttp( + mux *http.ServeMux, + handler func(c GetAllDataOfTheParticularProductOfferActionRequest) (*GetAllDataOfTheParticularProductOfferActionResponse, error), +) { + method, pattern, h := GetAllDataOfTheParticularProductOfferActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.go b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.go index 176824bf..43e7fd8b 100644 --- a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.go +++ b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.go @@ -393,3 +393,65 @@ func (x GetEventsAboutTheSellerSOffersActionRequest) IsCli() bool { } return true } + +// GetEventsAboutTheSellerSOffersActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetEventsAboutTheSellerSOffersAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetEventsAboutTheSellerSOffersActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetEventsAboutTheSellerSOffersActionHttpHandler( + handler func(c GetEventsAboutTheSellerSOffersActionRequest) (*GetEventsAboutTheSellerSOffersActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetEventsAboutTheSellerSOffersActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetEventsAboutTheSellerSOffersActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetEventsAboutTheSellerSOffersActionHttp is a high-level convenience wrapper around +// GetEventsAboutTheSellerSOffersActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetEventsAboutTheSellerSOffersActionHttp( + mux *http.ServeMux, + handler func(c GetEventsAboutTheSellerSOffersActionRequest) (*GetEventsAboutTheSellerSOffersActionResponse, error), +) { + method, pattern, h := GetEventsAboutTheSellerSOffersActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.go b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.go index eb9a2ef0..7a3cd743 100644 --- a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.go +++ b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.go @@ -567,3 +567,65 @@ func (x GetSelectedDataOfTheParticularProductOfferActionRequest) IsCli() bool { } return true } + +// GetSelectedDataOfTheParticularProductOfferActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetSelectedDataOfTheParticularProductOfferAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetSelectedDataOfTheParticularProductOfferActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetSelectedDataOfTheParticularProductOfferActionHttpHandler( + handler func(c GetSelectedDataOfTheParticularProductOfferActionRequest) (*GetSelectedDataOfTheParticularProductOfferActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetSelectedDataOfTheParticularProductOfferActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetSelectedDataOfTheParticularProductOfferActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetSelectedDataOfTheParticularProductOfferActionHttp is a high-level convenience wrapper around +// GetSelectedDataOfTheParticularProductOfferActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetSelectedDataOfTheParticularProductOfferActionHttp( + mux *http.ServeMux, + handler func(c GetSelectedDataOfTheParticularProductOfferActionRequest) (*GetSelectedDataOfTheParticularProductOfferActionResponse, error), +) { + method, pattern, h := GetSelectedDataOfTheParticularProductOfferActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSellersOffersAction.go b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSellersOffersAction.go index 54f2b522..6097a93d 100644 --- a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSellersOffersAction.go +++ b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSellersOffersAction.go @@ -1175,3 +1175,65 @@ func (x GetSellersOffersActionRequest) IsCli() bool { } return true } + +// GetSellersOffersActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetSellersOffersAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetSellersOffersActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetSellersOffersActionHttpHandler( + handler func(c GetSellersOffersActionRequest) (*GetSellersOffersActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetSellersOffersActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetSellersOffersActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetSellersOffersActionHttp is a high-level convenience wrapper around +// GetSellersOffersActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetSellersOffersActionHttp( + mux *http.ServeMux, + handler func(c GetSellersOffersActionRequest) (*GetSellersOffersActionResponse, error), +) { + method, pattern, h := GetSellersOffersActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.go b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.go index 7a21f628..20eb945b 100644 --- a/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.go +++ b/examples/allegro-sdk/golang/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.go @@ -487,3 +487,65 @@ func (x GetSmartClassificationReportOfTheParticularOfferActionRequest) IsCli() b } return true } + +// GetSmartClassificationReportOfTheParticularOfferActionHttpHandler returns the HTTP method, the ServeMux pattern, and a +// typed net/http handler for the GetSmartClassificationReportOfTheParticularOfferAction action. Developers implement +// their business logic as a function that receives a typed request object and +// returns either an *GetSmartClassificationReportOfTheParticularOfferActionResponse or nil. JSON marshalling, headers, +// status codes, and errors are handled automatically. +func GetSmartClassificationReportOfTheParticularOfferActionHttpHandler( + handler func(c GetSmartClassificationReportOfTheParticularOfferActionRequest) (*GetSmartClassificationReportOfTheParticularOfferActionResponse, error), +) (method, pattern string, h http.HandlerFunc) { + meta := GetSmartClassificationReportOfTheParticularOfferActionMeta() + return meta.Method, meta.URL, func(w http.ResponseWriter, r *http.Request) { + // Build typed request wrapper. GinCtx stays nil here (this is not gin), + // which is what the IsGin() helper keys off. + req := GetSmartClassificationReportOfTheParticularOfferActionRequest{ + Body: nil, + QueryParams: r.URL.Query(), + Headers: r.Header, + } + resp, err := handler(req) + if err != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + return + } + // If the handler returned nil (and no error), the response was handled + // manually. + if resp == nil { + return + } + // Apply headers + for k, v := range resp.Headers { + w.Header().Set(k, v) + } + // Apply status and payload + status := resp.StatusCode + if status == 0 { + status = http.StatusOK + } + if resp.Payload != nil { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(resp.Payload) + } else { + w.WriteHeader(status) + } + } +} + +// GetSmartClassificationReportOfTheParticularOfferActionHttp is a high-level convenience wrapper around +// GetSmartClassificationReportOfTheParticularOfferActionHttpHandler. It registers the typed route on a standard +// *http.ServeMux using Go 1.22+ method-aware pattern syntax (e.g. "POST /"). +// Use this when you don't need custom middleware. +func GetSmartClassificationReportOfTheParticularOfferActionHttp( + mux *http.ServeMux, + handler func(c GetSmartClassificationReportOfTheParticularOfferActionRequest) (*GetSmartClassificationReportOfTheParticularOfferActionResponse, error), +) { + method, pattern, h := GetSmartClassificationReportOfTheParticularOfferActionHttpHandler(handler) + mux.HandleFunc(method+" "+pattern, h) +} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.js index fc81c9f4..e03755e9 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -191,7 +184,7 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria} **/ - #offerCriteria = []; + #offerCriteria = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.OfferCriteria} @@ -204,23 +197,42 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria} **/ set offerCriteria(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.OfferCriteria + ) { + this.#offerCriteria = MArray.of(value); + } else { + this.#offerCriteria = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.OfferCriteria( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.OfferCriteria - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offerCriteria = value; - } else { - this.#offerCriteria = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.OfferCriteria( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offerCriteria = mcastValue; + return; + } + console.warn( + "Cannot assing value to offerCriteria, because it needs MArray instance or an Array.", + ); } setOfferCriteria(value) { this.offerCriteria = value; @@ -262,7 +274,7 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces} **/ - #additionalMarketplaces = []; + #additionalMarketplaces = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces} @@ -275,23 +287,42 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces} **/ set additionalMarketplaces(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces(value) { this.additionalMarketplaces = value; @@ -305,7 +336,7 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers} **/ - #offers = []; + #offers = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers} @@ -318,23 +349,42 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers} **/ set offers(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue; + return; } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } setOffers(value) { this.offers = value; @@ -621,7 +671,7 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages} @@ -634,24 +684,43 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.Modification + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.Modification - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; @@ -1148,7 +1217,7 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages} @@ -1161,24 +1230,43 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq + .AdditionalMarketplaces.Modification.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq - .AdditionalMarketplaces.Modification.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.js index 742ae593..194527d1 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -141,7 +134,7 @@ export class BatchOfferPublishUnpublishActionReq { * * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria} **/ - #offerCriteria = []; + #offerCriteria = MArray.of([]); /** * * @returns {BatchOfferPublishUnpublishActionReq.OfferCriteria} @@ -154,19 +147,39 @@ export class BatchOfferPublishUnpublishActionReq { * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria} **/ set offerCriteria(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof BatchOfferPublishUnpublishActionReq.OfferCriteria + ) { + this.#offerCriteria = MArray.of(value); + } else { + this.#offerCriteria = MArray.of( + value.map( + (item) => + new BatchOfferPublishUnpublishActionReq.OfferCriteria(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof BatchOfferPublishUnpublishActionReq.OfferCriteria - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offerCriteria = value; - } else { - this.#offerCriteria = value.map( - (item) => new BatchOfferPublishUnpublishActionReq.OfferCriteria(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offerCriteria = mcastValue; + return; } + console.warn( + "Cannot assing value to offerCriteria, because it needs MArray instance or an Array.", + ); } setOfferCriteria(value) { this.offerCriteria = value; @@ -210,7 +223,7 @@ export class BatchOfferPublishUnpublishActionReq { * * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers} **/ - #offers = []; + #offers = MArray.of([]); /** * * @returns {BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers} @@ -223,21 +236,42 @@ export class BatchOfferPublishUnpublishActionReq { * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers} **/ set offers(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map( + (item) => + new BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => - new BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue; + return; + } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } setOffers(value) { this.offers = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.js index 159bf1f2..6ff2e760 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.js @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/CreateOfferBasedOnProductAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/CreateOfferBasedOnProductAction.js index f08a3a10..4110901d 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/CreateOfferBasedOnProductAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/CreateOfferBasedOnProductAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -722,7 +715,7 @@ export class CreateOfferBasedOnProductActionReq { * Product details and associated quantities * @type {CreateOfferBasedOnProductActionReq.ProductSet} **/ - #productSet = []; + #productSet = MArray.of([]); /** * Product details and associated quantities * @returns {CreateOfferBasedOnProductActionReq.ProductSet} @@ -735,19 +728,38 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.ProductSet} **/ set productSet(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof CreateOfferBasedOnProductActionReq.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map( + (item) => new CreateOfferBasedOnProductActionReq.ProductSet(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof CreateOfferBasedOnProductActionReq.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => new CreateOfferBasedOnProductActionReq.ProductSet(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue; + return; } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } setProductSet(value) { this.productSet = value; @@ -1034,7 +1046,7 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.Attachments} **/ - #attachments = []; + #attachments = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.Attachments} @@ -1047,19 +1059,38 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.Attachments} **/ set attachments(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof CreateOfferBasedOnProductActionReq.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map( + (item) => new CreateOfferBasedOnProductActionReq.Attachments(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof CreateOfferBasedOnProductActionReq.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => new CreateOfferBasedOnProductActionReq.Attachments(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue; + return; + } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments(value) { this.attachments = value; @@ -1665,7 +1696,7 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.ProductSet.Deposits} **/ - #deposits = []; + #deposits = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.ProductSet.Deposits} @@ -1678,21 +1709,42 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.ProductSet.Deposits} **/ set deposits(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.ProductSet.Deposits( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.ProductSet.Deposits(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue; + return; + } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits(value) { this.deposits = value; @@ -1809,7 +1861,7 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters} **/ - #parameters = []; + #parameters = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters} @@ -1822,23 +1874,42 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters} **/ set parameters(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters(value) { this.parameters = value; @@ -5012,7 +5083,7 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.CompatibilityList.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.CompatibilityList.Items} @@ -5025,23 +5096,42 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.CompatibilityList.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.CompatibilityList.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.CompatibilityList.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.CompatibilityList.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.CompatibilityList.Items( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; @@ -5294,7 +5384,7 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.Description.Sections} **/ - #sections = []; + #sections = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.Description.Sections} @@ -5307,21 +5397,42 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.Description.Sections} **/ set sections(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.Description.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.Description.Sections(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue; + return; } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections(value) { this.sections = value; @@ -5335,7 +5446,7 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.Description.Sections.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.Description.Sections.Items} @@ -5348,23 +5459,42 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.Description.Sections.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.Description.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.Description.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.Description.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.Description.Sections.Items( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; @@ -7810,7 +7940,7 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.TaxSettings.Rates} **/ - #rates = []; + #rates = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.TaxSettings.Rates} @@ -7823,20 +7953,40 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.TaxSettings.Rates} **/ set rates(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.TaxSettings.Rates(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof CreateOfferBasedOnProductActionReq.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.TaxSettings.Rates(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue; + return; } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates(value) { this.rates = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/EditAnOfferAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/EditAnOfferAction.js index e3e6dc03..63d63d98 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/EditAnOfferAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/EditAnOfferAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -1420,7 +1413,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.ProductSet} **/ - #productSet = []; + #productSet = MArray.of([]); /** * * @returns {EditAnOfferActionReq.ProductSet} @@ -1433,19 +1426,36 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.ProductSet} **/ set productSet(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map((item) => new EditAnOfferActionReq.ProductSet(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => new EditAnOfferActionReq.ProductSet(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue; + return; + } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } setProductSet(value) { this.productSet = value; @@ -1727,7 +1737,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.Attachments} **/ - #attachments = []; + #attachments = MArray.of([]); /** * * @returns {EditAnOfferActionReq.Attachments} @@ -1740,19 +1750,36 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.Attachments} **/ set attachments(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map((item) => new EditAnOfferActionReq.Attachments(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => new EditAnOfferActionReq.Attachments(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue; + return; } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments(value) { this.attachments = value; @@ -2331,7 +2358,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.ProductSet.Deposits} **/ - #deposits = []; + #deposits = MArray.of([]); /** * * @returns {EditAnOfferActionReq.ProductSet.Deposits} @@ -2344,19 +2371,38 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.ProductSet.Deposits} **/ set deposits(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.ProductSet.Deposits(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => new EditAnOfferActionReq.ProductSet.Deposits(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue; + return; + } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits(value) { this.deposits = value; @@ -2469,7 +2515,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.ProductSet.Product.Parameters} **/ - #parameters = []; + #parameters = MArray.of([]); /** * * @returns {EditAnOfferActionReq.ProductSet.Product.Parameters} @@ -2482,20 +2528,40 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.ProductSet.Product.Parameters} **/ set parameters(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionReq.ProductSet.Product.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new EditAnOfferActionReq.ProductSet.Product.Parameters(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.ProductSet.Product.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new EditAnOfferActionReq.ProductSet.Product.Parameters(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters(value) { this.parameters = value; @@ -5586,7 +5652,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.CompatibilityList.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {EditAnOfferActionReq.CompatibilityList.Items} @@ -5599,19 +5665,38 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.CompatibilityList.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.CompatibilityList.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.CompatibilityList.Items(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.CompatibilityList.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => new EditAnOfferActionReq.CompatibilityList.Items(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; @@ -5856,7 +5941,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.Description.Sections} **/ - #sections = []; + #sections = MArray.of([]); /** * * @returns {EditAnOfferActionReq.Description.Sections} @@ -5869,19 +5954,38 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.Description.Sections} **/ set sections(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.Description.Sections(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => new EditAnOfferActionReq.Description.Sections(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue; + return; + } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections(value) { this.sections = value; @@ -5895,7 +5999,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.Description.Sections.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {EditAnOfferActionReq.Description.Sections.Items} @@ -5908,19 +6012,39 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.Description.Sections.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.Description.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new EditAnOfferActionReq.Description.Sections.Items(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.Description.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => new EditAnOfferActionReq.Description.Sections.Items(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; @@ -8307,7 +8431,7 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.TaxSettings.Rates} **/ - #rates = []; + #rates = MArray.of([]); /** * * @returns {EditAnOfferActionReq.TaxSettings.Rates} @@ -8320,19 +8444,38 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.TaxSettings.Rates} **/ set rates(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.TaxSettings.Rates(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => new EditAnOfferActionReq.TaxSettings.Rates(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue; + return; } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates(value) { this.rates = value; @@ -9219,7 +9362,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.ProductSet} **/ - #productSet = []; + #productSet = MArray.of([]); /** * * @returns {EditAnOfferActionRes.ProductSet} @@ -9232,19 +9375,36 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.ProductSet} **/ set productSet(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map((item) => new EditAnOfferActionRes.ProductSet(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => new EditAnOfferActionRes.ProductSet(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue; + return; } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } setProductSet(value) { this.productSet = value; @@ -9618,7 +9778,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Attachments} **/ - #attachments = []; + #attachments = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Attachments} @@ -9631,19 +9791,36 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Attachments} **/ set attachments(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map((item) => new EditAnOfferActionRes.Attachments(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => new EditAnOfferActionRes.Attachments(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue; + return; + } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments(value) { this.attachments = value; @@ -10233,7 +10410,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.ProductSet.Deposits} **/ - #deposits = []; + #deposits = MArray.of([]); /** * * @returns {EditAnOfferActionRes.ProductSet.Deposits} @@ -10246,19 +10423,38 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.ProductSet.Deposits} **/ set deposits(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.ProductSet.Deposits(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => new EditAnOfferActionRes.ProductSet.Deposits(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue; + return; } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits(value) { this.deposits = value; @@ -10463,7 +10659,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.ProductSet.Product.Parameters} **/ - #parameters = []; + #parameters = MArray.of([]); /** * * @returns {EditAnOfferActionRes.ProductSet.Product.Parameters} @@ -10476,20 +10672,40 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.ProductSet.Product.Parameters} **/ set parameters(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionRes.ProductSet.Product.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.ProductSet.Product.Parameters(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.ProductSet.Product.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new EditAnOfferActionRes.ProductSet.Product.Parameters(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters(value) { this.parameters = value; @@ -13357,7 +13573,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Publication.Marketplaces.Additional} **/ - #additional = []; + #additional = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Publication.Marketplaces.Additional} @@ -13370,23 +13586,42 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Publication.Marketplaces.Additional} **/ set additional(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionRes.Publication.Marketplaces.Additional + ) { + this.#additional = MArray.of(value); + } else { + this.#additional = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.Publication.Marketplaces.Additional( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - EditAnOfferActionRes.Publication.Marketplaces.Additional - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additional = value; - } else { - this.#additional = value.map( - (item) => - new EditAnOfferActionRes.Publication.Marketplaces.Additional( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additional = mcastValue; + return; } + console.warn( + "Cannot assing value to additional, because it needs MArray instance or an Array.", + ); } setAdditional(value) { this.additional = value; @@ -14275,7 +14510,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons} **/ - #refusalReasons = []; + #refusalReasons = MArray.of([]); /** * * @returns {EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons} @@ -14288,24 +14523,43 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons} **/ set refusalReasons(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionRes.AdditionalMarketplaces.Publication + .RefusalReasons + ) { + this.#refusalReasons = MArray.of(value); + } else { + this.#refusalReasons = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - EditAnOfferActionRes.AdditionalMarketplaces.Publication - .RefusalReasons - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#refusalReasons = value; - } else { - this.#refusalReasons = value.map( - (item) => - new EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#refusalReasons = mcastValue; + return; } + console.warn( + "Cannot assing value to refusalReasons, because it needs MArray instance or an Array.", + ); } setRefusalReasons(value) { this.refusalReasons = value; @@ -15121,7 +15375,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Validation.Errors} **/ - #errors = []; + #errors = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Validation.Errors} @@ -15134,19 +15388,38 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Validation.Errors} **/ set errors(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Validation.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.Validation.Errors(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Validation.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => new EditAnOfferActionRes.Validation.Errors(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue; + return; } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors(value) { this.errors = value; @@ -15156,7 +15429,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Validation.Warnings} **/ - #warnings = []; + #warnings = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Validation.Warnings} @@ -15169,19 +15442,38 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Validation.Warnings} **/ set warnings(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Validation.Warnings + ) { + this.#warnings = MArray.of(value); + } else { + this.#warnings = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.Validation.Warnings(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Validation.Warnings - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#warnings = value; - } else { - this.#warnings = value.map( - (item) => new EditAnOfferActionRes.Validation.Warnings(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#warnings = mcastValue; + return; + } + console.warn( + "Cannot assing value to warnings, because it needs MArray instance or an Array.", + ); } setWarnings(value) { this.warnings = value; @@ -17843,7 +18135,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.TaxSettings.Rates} **/ - #rates = []; + #rates = MArray.of([]); /** * * @returns {EditAnOfferActionRes.TaxSettings.Rates} @@ -17856,19 +18148,38 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.TaxSettings.Rates} **/ set rates(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.TaxSettings.Rates(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => new EditAnOfferActionRes.TaxSettings.Rates(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue; + return; + } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates(value) { this.rates = value; @@ -18259,7 +18570,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Description.Sections} **/ - #sections = []; + #sections = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Description.Sections} @@ -18272,19 +18583,38 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Description.Sections} **/ set sections(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.Description.Sections(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => new EditAnOfferActionRes.Description.Sections(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue; + return; + } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections(value) { this.sections = value; @@ -18298,7 +18628,7 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Description.Sections.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Description.Sections.Items} @@ -18311,19 +18641,39 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Description.Sections.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Description.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.Description.Sections.Items(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Description.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => new EditAnOfferActionRes.Description.Sections.Items(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.js index 1a3d86ed..c2470017 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -183,7 +176,7 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.BasePackages} **/ - #basePackages = []; + #basePackages = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.BasePackages} @@ -196,21 +189,42 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.BasePackages} **/ set basePackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes.BasePackages + ) { + this.#basePackages = MArray.of(value); + } else { + this.#basePackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.BasePackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.BasePackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#basePackages = value; - } else { - this.#basePackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.BasePackages(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#basePackages = mcastValue; + return; } + console.warn( + "Cannot assing value to basePackages, because it needs MArray instance or an Array.", + ); } setBasePackages(value) { this.basePackages = value; @@ -220,7 +234,7 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages} @@ -233,23 +247,42 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; @@ -259,7 +292,7 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces = []; + #additionalMarketplaces = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces} @@ -272,23 +305,42 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces(value) { this.additionalMarketplaces = value; @@ -669,7 +721,7 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages} **/ - #basePackages = []; + #basePackages = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages} @@ -682,24 +734,43 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages} **/ set basePackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes + .AdditionalMarketplaces.BasePackages + ) { + this.#basePackages = MArray.of(value); + } else { + this.#basePackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - .BasePackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#basePackages = value; - } else { - this.#basePackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#basePackages = mcastValue; + return; + } + console.warn( + "Cannot assing value to basePackages, because it needs MArray instance or an Array.", + ); } setBasePackages(value) { this.basePackages = value; @@ -709,7 +780,7 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} @@ -722,24 +793,43 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes + .AdditionalMarketplaces.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOfferPromotionPackagesAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOfferPromotionPackagesAction.js index f8ea0192..4b51eabc 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOfferPromotionPackagesAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOfferPromotionPackagesAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -308,7 +301,7 @@ export class GetOfferPromotionPackagesActionRes { * * @type {GetOfferPromotionPackagesActionRes.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {GetOfferPromotionPackagesActionRes.ExtraPackages} @@ -321,19 +314,39 @@ export class GetOfferPromotionPackagesActionRes { * @type {GetOfferPromotionPackagesActionRes.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetOfferPromotionPackagesActionRes.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetOfferPromotionPackagesActionRes.ExtraPackages(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetOfferPromotionPackagesActionRes.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => new GetOfferPromotionPackagesActionRes.ExtraPackages(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; @@ -372,7 +385,7 @@ export class GetOfferPromotionPackagesActionRes { * * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces = []; + #additionalMarketplaces = MArray.of([]); /** * * @returns {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces} @@ -385,21 +398,42 @@ export class GetOfferPromotionPackagesActionRes { * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferPromotionPackagesActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue; + return; } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces(value) { this.additionalMarketplaces = value; @@ -1220,7 +1254,7 @@ export class GetOfferPromotionPackagesActionRes { * * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} @@ -1233,24 +1267,43 @@ export class GetOfferPromotionPackagesActionRes { * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferPromotionPackagesActionRes.AdditionalMarketplaces - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOffersWithMissingParametersAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOffersWithMissingParametersAction.js index d1351ea8..c424ff41 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOffersWithMissingParametersAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetOffersWithMissingParametersAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -111,7 +104,7 @@ export class GetOffersWithMissingParametersActionRes { * * @type {GetOffersWithMissingParametersActionRes.Offers} **/ - #offers = []; + #offers = MArray.of([]); /** * * @returns {GetOffersWithMissingParametersActionRes.Offers} @@ -124,19 +117,38 @@ export class GetOffersWithMissingParametersActionRes { * @type {GetOffersWithMissingParametersActionRes.Offers} **/ set offers(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetOffersWithMissingParametersActionRes.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map( + (item) => new GetOffersWithMissingParametersActionRes.Offers(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetOffersWithMissingParametersActionRes.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => new GetOffersWithMissingParametersActionRes.Offers(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue; + return; + } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } setOffers(value) { this.offers = value; @@ -227,7 +239,7 @@ export class GetOffersWithMissingParametersActionRes { * * @type {GetOffersWithMissingParametersActionRes.Offers.Parameters} **/ - #parameters = []; + #parameters = MArray.of([]); /** * * @returns {GetOffersWithMissingParametersActionRes.Offers.Parameters} @@ -240,21 +252,42 @@ export class GetOffersWithMissingParametersActionRes { * @type {GetOffersWithMissingParametersActionRes.Offers.Parameters} **/ set parameters(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOffersWithMissingParametersActionRes.Offers.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new GetOffersWithMissingParametersActionRes.Offers.Parameters( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOffersWithMissingParametersActionRes.Offers.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new GetOffersWithMissingParametersActionRes.Offers.Parameters(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue; + return; + } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters(value) { this.parameters = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.js index e59ff36a..f09b70a2 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -249,7 +242,7 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions} **/ - #promoOptions = []; + #promoOptions = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions} @@ -262,20 +255,40 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions} **/ set promoOptions(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions + ) { + this.#promoOptions = MArray.of(value); + } else { + this.#promoOptions = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetPromoOptionsForSellerSOffersActionRes.PromoOptions - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#promoOptions = value; - } else { - this.#promoOptions = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#promoOptions = mcastValue; + return; + } + console.warn( + "Cannot assing value to promoOptions, because it needs MArray instance or an Array.", + ); } setPromoOptions(value) { this.promoOptions = value; @@ -423,7 +436,7 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages} @@ -436,23 +449,42 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; @@ -496,7 +528,7 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces} **/ - #additionalMarketplaces = []; + #additionalMarketplaces = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces} @@ -509,24 +541,43 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces} **/ set additionalMarketplaces(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions + .AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetPromoOptionsForSellerSOffersActionRes.PromoOptions - .AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces(value) { this.additionalMarketplaces = value; @@ -1349,7 +1400,7 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages} @@ -1362,24 +1413,43 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions + .AdditionalMarketplaces.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetPromoOptionsForSellerSOffersActionRes.PromoOptions - .AdditionalMarketplaces.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandDetailedResultAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandDetailedResultAction.js index 40e35244..cb6ac671 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandDetailedResultAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandDetailedResultAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -210,7 +203,7 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.Tasks} **/ - #tasks = []; + #tasks = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.Tasks} @@ -223,19 +216,39 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.Tasks} **/ set tasks(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof ModificationCommandDetailedResultActionRes.Tasks + ) { + this.#tasks = MArray.of(value); + } else { + this.#tasks = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.Tasks(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModificationCommandDetailedResultActionRes.Tasks - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#tasks = value; - } else { - this.#tasks = value.map( - (item) => new ModificationCommandDetailedResultActionRes.Tasks(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#tasks = mcastValue; + return; } + console.warn( + "Cannot assing value to tasks, because it needs MArray instance or an Array.", + ); } setTasks(value) { this.tasks = value; @@ -276,7 +289,7 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces = []; + #additionalMarketplaces = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces} @@ -289,23 +302,42 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue; + return; } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces(value) { this.additionalMarketplaces = value; @@ -442,7 +474,7 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.Tasks.Errors} **/ - #errors = []; + #errors = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.Tasks.Errors} @@ -455,21 +487,42 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.Tasks.Errors} **/ set errors(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.Tasks.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.Tasks.Errors( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.Tasks.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.Tasks.Errors(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue; + return; } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors(value) { this.errors = value; @@ -1185,7 +1238,7 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.Modification.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.Modification.ExtraPackages} @@ -1198,23 +1251,43 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.Modification.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.Modification + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.Modification.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.Modification.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; @@ -1710,7 +1783,7 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages} @@ -1723,24 +1796,43 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + .Modification.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.AdditionalMarketplaces - .Modification.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandSummaryAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandSummaryAction.js index 63fe19a9..0a104a05 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandSummaryAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModificationCommandSummaryAction.js @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.js index 3d1a7726..56ac09c4 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -285,7 +278,7 @@ export class ModifyOfferPromotionPackagesActionReq { * * @type {ModifyOfferPromotionPackagesActionReq.Modifications} **/ - #modifications = []; + #modifications = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionReq.Modifications} @@ -298,19 +291,39 @@ export class ModifyOfferPromotionPackagesActionReq { * @type {ModifyOfferPromotionPackagesActionReq.Modifications} **/ set modifications(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof ModifyOfferPromotionPackagesActionReq.Modifications + ) { + this.#modifications = MArray.of(value); + } else { + this.#modifications = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionReq.Modifications(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModifyOfferPromotionPackagesActionReq.Modifications - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#modifications = value; - } else { - this.#modifications = value.map( - (item) => new ModifyOfferPromotionPackagesActionReq.Modifications(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#modifications = mcastValue; + return; } + console.warn( + "Cannot assing value to modifications, because it needs MArray instance or an Array.", + ); } setModifications(value) { this.modifications = value; @@ -320,7 +333,7 @@ export class ModifyOfferPromotionPackagesActionReq { * * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces} **/ - #additionalMarketplaces = []; + #additionalMarketplaces = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces} @@ -333,23 +346,42 @@ export class ModifyOfferPromotionPackagesActionReq { * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces} **/ set additionalMarketplaces(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces(value) { this.additionalMarketplaces = value; @@ -558,7 +590,7 @@ export class ModifyOfferPromotionPackagesActionReq { * * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications} **/ - #modifications = []; + #modifications = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications} @@ -571,24 +603,43 @@ export class ModifyOfferPromotionPackagesActionReq { * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications} **/ set modifications(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + .Modifications + ) { + this.#modifications = MArray.of(value); + } else { + this.#modifications = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces - .Modifications - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#modifications = value; - } else { - this.#modifications = value.map( - (item) => - new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#modifications = mcastValue; + return; } + console.warn( + "Cannot assing value to modifications, because it needs MArray instance or an Array.", + ); } setModifications(value) { this.modifications = value; @@ -1050,7 +1101,7 @@ export class ModifyOfferPromotionPackagesActionRes { * * @type {ModifyOfferPromotionPackagesActionRes.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionRes.ExtraPackages} @@ -1063,19 +1114,39 @@ export class ModifyOfferPromotionPackagesActionRes { * @type {ModifyOfferPromotionPackagesActionRes.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof ModifyOfferPromotionPackagesActionRes.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionRes.ExtraPackages(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModifyOfferPromotionPackagesActionRes.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => new ModifyOfferPromotionPackagesActionRes.ExtraPackages(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; @@ -1114,7 +1185,7 @@ export class ModifyOfferPromotionPackagesActionRes { * * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces = []; + #additionalMarketplaces = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces} @@ -1127,23 +1198,42 @@ export class ModifyOfferPromotionPackagesActionRes { * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces(value) { this.additionalMarketplaces = value; @@ -1966,7 +2056,7 @@ export class ModifyOfferPromotionPackagesActionRes { * * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages = []; + #extraPackages = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} @@ -1979,24 +2069,43 @@ export class ModifyOfferPromotionPackagesActionRes { * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages(value) { this.extraPackages = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.js index 0a2000af..87e01e87 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -1019,7 +1012,7 @@ export class ModifyTheBuyNowPriceInAnOfferActionRes { * * @type {ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors} **/ - #errors = []; + #errors = MArray.of([]); /** * * @returns {ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors} @@ -1032,20 +1025,40 @@ export class ModifyTheBuyNowPriceInAnOfferActionRes { * @type {ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors} **/ set errors(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue; + return; + } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors(value) { this.errors = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandDetailedReportAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandDetailedReportAction.js index 6107c91d..ee21dbe1 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandDetailedReportAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandDetailedReportAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -137,7 +130,7 @@ export class PublishCommandDetailedReportActionRes { * * @type {PublishCommandDetailedReportActionRes.Tasks} **/ - #tasks = []; + #tasks = MArray.of([]); /** * * @returns {PublishCommandDetailedReportActionRes.Tasks} @@ -150,19 +143,38 @@ export class PublishCommandDetailedReportActionRes { * @type {PublishCommandDetailedReportActionRes.Tasks} **/ set tasks(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof PublishCommandDetailedReportActionRes.Tasks + ) { + this.#tasks = MArray.of(value); + } else { + this.#tasks = MArray.of( + value.map( + (item) => new PublishCommandDetailedReportActionRes.Tasks(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof PublishCommandDetailedReportActionRes.Tasks - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#tasks = value; - } else { - this.#tasks = value.map( - (item) => new PublishCommandDetailedReportActionRes.Tasks(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#tasks = mcastValue; + return; } + console.warn( + "Cannot assing value to tasks, because it needs MArray instance or an Array.", + ); } setTasks(value) { this.tasks = value; @@ -275,7 +287,7 @@ export class PublishCommandDetailedReportActionRes { * * @type {PublishCommandDetailedReportActionRes.Tasks.Errors} **/ - #errors = []; + #errors = MArray.of([]); /** * * @returns {PublishCommandDetailedReportActionRes.Tasks.Errors} @@ -288,20 +300,39 @@ export class PublishCommandDetailedReportActionRes { * @type {PublishCommandDetailedReportActionRes.Tasks.Errors} **/ set errors(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof PublishCommandDetailedReportActionRes.Tasks.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new PublishCommandDetailedReportActionRes.Tasks.Errors(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof PublishCommandDetailedReportActionRes.Tasks.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new PublishCommandDetailedReportActionRes.Tasks.Errors(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue; + return; + } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors(value) { this.errors = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandSummaryAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandSummaryAction.js index cddc409e..5b4dee2e 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandSummaryAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-management/PublishCommandSummaryAction.js @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/buildUrl.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/buildUrl.ts deleted file mode 100644 index cf08f1cc..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/buildUrl.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Handy tool to create a final callable url, from query string, query params, - * and the actual url. - * @param template - * @param params - * @param qs - * @returns - */ -export function buildUrl( - url: string, - params?: Record, - qs?: URLSearchParams -) { - // Replace :placeholders - if (params) { - Object.entries(params as Record).forEach(([key, value]) => { - url = url.replace( - new RegExp(`:${key}`, "g"), - encodeURIComponent(String(value)) - ); - }); - } - - if (qs && qs instanceof URLSearchParams) { - url += `?${qs.toString()}`; - } else if (qs && Object.keys(qs).length) { - const query = new URLSearchParams( - Object.entries(qs).map(([k, v]) => [k, String(v)]) - ).toString(); - url += `?${query}`; - } - - return url; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/fetchx.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/fetchx.ts deleted file mode 100644 index 774f16b0..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/fetchx.ts +++ /dev/null @@ -1,196 +0,0 @@ -export type TypedRequestInit = Omit< - RequestInit, - "body" | "headers" -> & { - body?: TBody; - headers?: THeaders; -}; -export class TypedResponse extends Response { - override json(): Promise { - return super.json(); - } - result: - | T - | undefined - | ReadableStream> - | null - | string; -} -export async function fetchx< - TResponse = unknown, - TBody = unknown, - THeaders = unknown, ->( - input: RequestInfo | URL, - init?: TypedRequestInit, - ctx?: FetchxContext | null, -): Promise> { - let url = input.toString(); - let reqInit: TypedRequestInit = init || {}; - let res: TypedResponse; - let fetchFn = fetch; - - if (ctx) { - [url, reqInit] = await ctx.apply(url, reqInit); - - if (ctx.fetchOverrideFn) { - fetchFn = ctx.fetchOverrideFn; - } - } - - res = (await fetchFn( - url, - reqInit as RequestInit, - )) as TypedResponse; - - if (ctx) { - res = await ctx.handle(res); - } - return res; -} -type DtoFactory = { new (data: any): T } | ((data: any) => T); -function isConstructor(fn: DtoFactory): fn is { new (data: any): T } { - return ( - typeof fn === "function" && fn.prototype && fn.prototype.constructor === fn - ); -} -export async function handleFetchResponse( - res: TypedResponse, - dto?: DtoFactory, - onMessage?: (msg: any) => void, - signal?: AbortSignal | null, -): Promise<{ done: Promise; response: TypedResponse }> { - const ct = res.headers.get("content-type") || ""; - const cd = res.headers.get("content-disposition") || ""; - if (ct.includes("text/event-stream")) { - return SSEFetch(res, onMessage, signal); - } - if ( - cd.includes("attachment") || - (!ct.includes("json") && !ct.startsWith("text/")) - ) { - (res as any).result = res.body; - } else if (ct.includes("application/json")) { - const json = await res.json(); - if (dto) { - if (isConstructor(dto)) { - (res as any).result = new dto(json); // ✅ class constructor - } else { - (res as any).result = dto(json); // ✅ factory function - } - } else { - (res as any).result = json; - } - } else { - (res as any).result = await res.text(); - } - return { done: Promise.resolve(), response: res as any }; -} -export const SSEFetch = ( - res: TypedResponse, - onMessage?: (ev: MessageEvent) => void, - signal?: AbortSignal | null, -): { response: TypedResponse; done: Promise } => { - if (!res.body) throw new Error("SSE requires readable body"); - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - const done = new Promise((resolve, reject) => { - function readChunk() { - reader - .read() - .then(({ done: finished, value }) => { - if (signal?.aborted) { - reader.cancel(); - return resolve(); // resolve on abort - } - if (finished) return resolve(); // normal end - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split("\n\n"); - buffer = parts.pop() || ""; - for (const part of parts) { - let data = ""; - let event = "message"; - part.split("\n").forEach((line) => { - if (line.startsWith("data:")) data += line.slice(5).trim(); - else if (line.startsWith("event:")) event = line.slice(6).trim(); - }); - if (data) { - if (data === "[DONE]") return resolve(); - onMessage?.(new MessageEvent(event, { data })); - } - } - readChunk(); - }) - .catch((err) => { - if (err.name === "AbortError") resolve(); - else reject(err); - }); - } - readChunk(); - }); - return { response: res, done }; -}; -export class FetchxContext { - constructor( - public baseUrl: string = "", - public defaultHeaders: Record = {}, - public requestInterceptor?: ( - url: string, - init: TypedRequestInit, - ) => - | Promise<[string, TypedRequestInit]> - | [string, TypedRequestInit], - public responseInterceptor?: ( - res: TypedResponse, - ) => Promise>, - /** - * Overrides the browser fetch function, for different purposes. It would recieve the same first 2 arguments as fetch, - * as well as third one of fetchx context. If you pass the fetch itself to override, it should have no effect. - */ - public fetchOverrideFn?: ( - input: RequestInfo | URL, - init?: TypedRequestInit, - ) => Promise, - ) {} - async apply( - url: string, - init: TypedRequestInit, - ): Promise<[string, TypedRequestInit]> { - // prefix baseUrl - if (!/^https?:\/\//.test(url)) { - url = this.baseUrl + url; - } - // merge default headers - (init.headers as unknown) = { - ...this.defaultHeaders, - ...((init.headers as object) || {}), - }; - // call request interceptor if present - if (this.requestInterceptor) { - return this.requestInterceptor(url, init); - } - return [url, init]; - } - async handle(res: TypedResponse): Promise> { - if (this.responseInterceptor) { - return this.responseInterceptor(res); - } - return res; - } - clone(overrides?: Partial): FetchxContext { - return new FetchxContext( - overrides?.baseUrl ?? this.baseUrl, - { ...this.defaultHeaders, ...(overrides?.defaultHeaders || {}) }, - overrides?.requestInterceptor ?? this.requestInterceptor, - overrides?.responseInterceptor ?? this.responseInterceptor, - ); - } -} -export type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; \ No newline at end of file diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/operators.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/operators.ts deleted file mode 100644 index 728da07e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/operators.ts +++ /dev/null @@ -1,173 +0,0 @@ -export class MOne { - private operation: string | null = null; - private selector: S | undefined; - - private content: T | undefined = undefined; - - isNull(): boolean { - return this.content === null; - } - - isSelector(): boolean { - return this.selector !== undefined && this.operation !== null; - } - - get(): T { - return this.content!; - } - - static of(value: T) { - const one = new MOne(); - one.content = value; - - return one; - } - - static select(selector: any) { - const one = new MOne(); - one.selector = selector; - one.operation = "replace"; - - return one; - } - - toJSON() { - // When its explicit replace, it means that we need to pass a selector, so reader will - // be able to replace it via internal mechanism - if (this.operation === "replace") { - return { - __operation: this.operation, - selector: this.selector, - }; - } - - return this.content; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, maybe just giving back one is enough. -export class MOneNullable extends MOne {} - -// Array describes how an incoming list should be applied to an existing one, -// mirroring emigo.Array on the Go side. It lets a PATCH-style payload say -// "replace the whole set" versus "append to the existing set". -// -// On the wire a "replace" is implicit (a bare array), while an "append" is -// tagged with __operation so the reader keeps the existing rows. This keeps -// the payload identical to the Go client/backend generators. -export class MArray { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "replace"; - - return arr; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "append"; - - return arr; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Array is enough. -export class MArrayNullable extends Array {} - -// Collection mirrors emigo.Collection on the Go side. Structurally it is the -// same as Array — a list carrying a "replace"/"append" operation — but it is a -// distinct field type: a collection holds a list of a target entity, whereas an -// array holds a list of an inline DTO. -export class MCollection { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "replace"; - - return collection; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "append"; - - return collection; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Collection is enough. -export class CollectionNullable extends MCollection {} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/withPrefix.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts deleted file mode 100644 index 850d7626..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * To declare a new envelope class, you must follow these rules: - * 1. The constructor must accept any object, which will contain the parsed JSON message - * from a response. - * 2. Envelope classes must provide a function to update the payload. Since payloads are - * type-safe, they must be instantiated and passed to the envelope; the common constructor - * alone is not enough. - * 3. Enveope must have a way to provide the content back actually, in order to create a class out of them. - */ - -export type CreatorSignature = (item: unknown) => T; - -export interface EnvelopeClass { - setCreator(fn: CreatorSignature): this; - inject(data: unknown): this; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts deleted file mode 100644 index 455cdd2e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; - -// Some responses are returning a flat array, without any other information -// regarding the pagination, etc. They start [{},{}...] style. -// For those which might have a single project which is array but none-standard, -// Use CaptureArray instead. - -export class FlatArray implements EnvelopeClass { - public data: T[] = []; - creator?: CreatorSignature | null = null; - - inject(data: unknown) { - if (!Array.isArray(data)) { - throw new Error( - "FlatArray can only work on flat array items, such as [{},...], and doesn't accept any other type" - ); - } - - if (typeof this.creator !== "undefined") { - this.data = data.map((item) => - (this.creator as CreatorSignature)(item) - ); - } else { - this.data = data; - } - - return this; - } - - setCreator(creator: CreatorSignature) { - this.creator = creator; - - return this; - } - - // Implement thigs here, which would make the flat array to act as an array actually, how can it become - // class instance as an array? -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts deleted file mode 100644 index 0c078ce3..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts +++ /dev/null @@ -1,1715 +0,0 @@ -import { withPrefix } from "./sdk/common/withPrefix"; -/** - * The base class definition for responseDto - **/ -export class ResponseDto { - /** - * Version of the API used for this response. - * @type {string} - **/ - #apiVersion?: string | null = undefined; - /** - * Version of the API used for this response. - * @returns {string} - **/ - get apiVersion() { - return this.#apiVersion; - } - /** - * Version of the API used for this response. - * @type {string} - **/ - set apiVersion(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#apiVersion = correctType ? value : String(value); - } - setApiVersion(value: string | null | undefined) { - this.apiVersion = value; - return this; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - #context?: string | null = undefined; - /** - * Context string provided by the client or system for request tracking. - * @returns {string} - **/ - get context() { - return this.#context; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - set context(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#context = correctType ? value : String(value); - } - setContext(value: string | null | undefined) { - this.context = value; - return this; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier assigned to the request/response. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - #method?: string | null = undefined; - /** - * Name of the API method invoked. - * @returns {string} - **/ - get method() { - return this.#method; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - set method(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#method = correctType ? value : String(value); - } - setMethod(value: string | null | undefined) { - this.method = value; - return this; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - #params: any = null; - /** - * Parameters sent with the request. - * @returns {any} - **/ - get params() { - return this.#params; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - set params(value: any) { - this.#params = value; - } - setParams(value: any) { - this.params = value; - return this; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - #data!: InstanceType>; - /** - * Main data payload of the response. - * @returns {ResponseDto.Data} - **/ - get data() { - return this.#data; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - set data(value: InstanceType>) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Data) { - this.#data = value; - } else { - this.#data = new ResponseDto.Data(value); - } - } - setData(value: InstanceType>) { - this.data = value; - return this; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - #error!: InstanceType; - /** - * Error details, if the request failed. - * @returns {ResponseDto.Error} - **/ - get error() { - return this.#error; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - set error(value: InstanceType) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Error) { - this.#error = value; - } else { - this.#error = new ResponseDto.Error(value); - } - } - setError(value: InstanceType) { - this.error = value; - return this; - } - /** - * The base class definition for data - **/ - static Data = class Data { - /** - * Single item returned by the API. - * @type {any} - **/ - #item: T | null = null; - /** - * Single item returned by the API. - * @returns {T} - **/ - get item(): T | null { - return this.#item; - } - /** - * Single item returned by the API. - * @type {any} - **/ - set item(value: any) { - this.#item = value; - } - setItem(value: any) { - this.item = value; - return this; - } - /** - * List of items returned by the API. - * @type {any} - **/ - #items: T[] = []; - /** - * List of items returned by the API. - * @returns {T[]} - **/ - get items(): T[] { - return this.#items; - } - /** - * List of items returned by the API. - * @type {T[]} - **/ - set items(value: T[]) { - this.#items = value; - } - setItems(value: T[]) { - this.items = value; - return this; - } - /** - * Link to edit this resource. - * @type {string} - **/ - #editLink?: string | null = undefined; - /** - * Link to edit this resource. - * @returns {string} - **/ - get editLink() { - return this.#editLink; - } - /** - * Link to edit this resource. - * @type {string} - **/ - set editLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#editLink = correctType ? value : String(value); - } - setEditLink(value: string | null | undefined) { - this.editLink = value; - return this; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - #selfLink?: string | null = undefined; - /** - * Link to retrieve this resource. - * @returns {string} - **/ - get selfLink() { - return this.#selfLink; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - set selfLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#selfLink = correctType ? value : String(value); - } - setSelfLink(value: string | null | undefined) { - this.selfLink = value; - return this; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - #kind?: string | null = undefined; - /** - * Resource type (kind) identifier. - * @returns {string} - **/ - get kind() { - return this.#kind; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - set kind(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#kind = correctType ? value : String(value); - } - setKind(value: string | null | undefined) { - this.kind = value; - return this; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - #fields?: string | null = undefined; - /** - * Selector specifying which fields are included in a partial response. - * @returns {string} - **/ - get fields() { - return this.#fields; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - set fields(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#fields = correctType ? value : String(value); - } - setFields(value: string | null | undefined) { - this.fields = value; - return this; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - #etag?: string | null = undefined; - /** - * ETag of the resource, used for caching/version control. - * @returns {string} - **/ - get etag() { - return this.#etag; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - set etag(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#etag = correctType ? value : String(value); - } - setEtag(value: string | null | undefined) { - this.etag = value; - return this; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - #cursor?: string | null = undefined; - /** - * Cursor for paginated data fetching. - * @returns {string} - **/ - get cursor() { - return this.#cursor; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - set cursor(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#cursor = correctType ? value : String(value); - } - setCursor(value: string | null | undefined) { - this.cursor = value; - return this; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier of the resource. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Language code of the response data. - * @type {string} - **/ - #lang?: string | null = undefined; - /** - * Language code of the response data. - * @returns {string} - **/ - get lang() { - return this.#lang; - } - /** - * Language code of the response data. - * @type {string} - **/ - set lang(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#lang = correctType ? value : String(value); - } - setLang(value: string | null | undefined) { - this.lang = value; - return this; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - #updated?: string | null = undefined; - /** - * Last modification time of the resource. - * @returns {string} - **/ - get updated() { - return this.#updated; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - set updated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#updated = correctType ? value : String(value); - } - setUpdated(value: string | null | undefined) { - this.updated = value; - return this; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - #currentItemCount?: number | null = undefined; - /** - * Number of items in the current response page. - * @returns {number} - **/ - get currentItemCount() { - return this.#currentItemCount; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - set currentItemCount(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#currentItemCount = parsedValue; - } - } - setCurrentItemCount(value: number | null | undefined) { - this.currentItemCount = value; - return this; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - #itemsPerPage?: number | null = undefined; - /** - * Maximum number of items per page. - * @returns {number} - **/ - get itemsPerPage() { - return this.#itemsPerPage; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - set itemsPerPage(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#itemsPerPage = parsedValue; - } - } - setItemsPerPage(value: number | null | undefined) { - this.itemsPerPage = value; - return this; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - #startIndex?: number | null = undefined; - /** - * Index of the first item in the current page. - * @returns {number} - **/ - get startIndex() { - return this.#startIndex; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - set startIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#startIndex = parsedValue; - } - } - setStartIndex(value: number | null | undefined) { - this.startIndex = value; - return this; - } - /** - * Total number of items available. - * @type {number} - **/ - #totalItems?: number | null = undefined; - /** - * Total number of items available. - * @returns {number} - **/ - get totalItems() { - return this.#totalItems; - } - /** - * Total number of items available. - * @type {number} - **/ - set totalItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalItems = parsedValue; - } - } - setTotalItems(value: number | null | undefined) { - this.totalItems = value; - return this; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - #totalAvailableItems?: number | null = undefined; - /** - * Number of items available for this user/query. - * @returns {number} - **/ - get totalAvailableItems() { - return this.#totalAvailableItems; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - set totalAvailableItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalAvailableItems = parsedValue; - } - } - setTotalAvailableItems(value: number | null | undefined) { - this.totalAvailableItems = value; - return this; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - #pageIndex?: number | null = undefined; - /** - * Current page index in the pagination. - * @returns {number} - **/ - get pageIndex() { - return this.#pageIndex; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - set pageIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#pageIndex = parsedValue; - } - } - setPageIndex(value: number | null | undefined) { - this.pageIndex = value; - return this; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - #totalPages?: number | null = undefined; - /** - * Total number of pages in the pagination. - * @returns {number} - **/ - get totalPages() { - return this.#totalPages; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - set totalPages(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalPages = parsedValue; - } - } - setTotalPages(value: number | null | undefined) { - this.totalPages = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.item !== undefined) { - this.item = d.item; - } - if (d.items !== undefined) { - this.items = d.items; - } - if (d.editLink !== undefined) { - this.editLink = d.editLink; - } - if (d.selfLink !== undefined) { - this.selfLink = d.selfLink; - } - if (d.kind !== undefined) { - this.kind = d.kind; - } - if (d.fields !== undefined) { - this.fields = d.fields; - } - if (d.etag !== undefined) { - this.etag = d.etag; - } - if (d.cursor !== undefined) { - this.cursor = d.cursor; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.lang !== undefined) { - this.lang = d.lang; - } - if (d.updated !== undefined) { - this.updated = d.updated; - } - if (d.currentItemCount !== undefined) { - this.currentItemCount = d.currentItemCount; - } - if (d.itemsPerPage !== undefined) { - this.itemsPerPage = d.itemsPerPage; - } - if (d.startIndex !== undefined) { - this.startIndex = d.startIndex; - } - if (d.totalItems !== undefined) { - this.totalItems = d.totalItems; - } - if (d.totalAvailableItems !== undefined) { - this.totalAvailableItems = d.totalAvailableItems; - } - if (d.pageIndex !== undefined) { - this.pageIndex = d.pageIndex; - } - if (d.totalPages !== undefined) { - this.totalPages = d.totalPages; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - item: this.#item, - items: this.#items, - editLink: this.#editLink, - selfLink: this.#selfLink, - kind: this.#kind, - fields: this.#fields, - etag: this.#etag, - cursor: this.#cursor, - id: this.#id, - lang: this.#lang, - updated: this.#updated, - currentItemCount: this.#currentItemCount, - itemsPerPage: this.#itemsPerPage, - startIndex: this.#startIndex, - totalItems: this.#totalItems, - totalAvailableItems: this.#totalAvailableItems, - pageIndex: this.#pageIndex, - totalPages: this.#totalPages, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - item: "item", - items: "items", - editLink: "editLink", - selfLink: "selfLink", - kind: "kind", - fields: "fields", - etag: "etag", - cursor: "cursor", - id: "id", - lang: "lang", - updated: "updated", - currentItemCount: "currentItemCount", - itemsPerPage: "itemsPerPage", - startIndex: "startIndex", - totalItems: "totalItems", - totalAvailableItems: "totalAvailableItems", - pageIndex: "pageIndex", - totalPages: "totalPages", - }; - } - /** - * Creates an instance of ResponseDto.Data, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.DataType) { - return new ResponseDto.Data(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Data, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep>, - ) { - return new ResponseDto.Data(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto.Data({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Data(this.toJSON()); - } - }; - /** - * The base class definition for error - **/ - static Error = class Error { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - #code: number = 0; - /** - * Numeric error code representing the failure. - * @returns {number} - **/ - get code() { - return this.#code; - } - /** - * Numeric error code representing the failure. - * @type {number} - **/ - set code(value: number) { - const correctType = typeof value === "number"; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#code = parsedValue; - } - } - setCode(value: number) { - this.code = value; - return this; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - #message: string = ""; - /** - * Human-readable explanation of the error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - set message(value: string) { - this.#message = String(value); - } - setMessage(value: string) { - this.message = value; - return this; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - #messageTranslated: string = ""; - /** - * Localized/translated version of the error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - set messageTranslated(value: string) { - this.#messageTranslated = String(value); - } - setMessageTranslated(value: string) { - this.messageTranslated = value; - return this; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - #errors: InstanceType[] = []; - /** - * Detailed list of error objects. - * @returns {ResponseDto.Error.Errors} - **/ - get errors() { - return this.#errors; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - set errors(value: InstanceType[]) { - // For arrays, you only can pass arrays to the object - if (!Array.isArray(value)) { - return; - } - if (value.length > 0 && value[0] instanceof ResponseDto.Error.Errors) { - this.#errors = value; - } else { - this.#errors = value.map((item) => new ResponseDto.Error.Errors(item)); - } - } - setErrors(value: InstanceType[]) { - this.errors = value; - return this; - } - /** - * The base class definition for errors - **/ - static Errors = class Errors { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - #domain?: string | null = undefined; - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @returns {string} - **/ - get domain() { - return this.#domain; - } - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - set domain(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#domain = correctType ? value : String(value); - } - setDomain(value: string | null | undefined) { - this.domain = value; - return this; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - #reason?: string | null = undefined; - /** - * Reason identifier for the error. - * @returns {string} - **/ - get reason() { - return this.#reason; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - set reason(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#reason = correctType ? value : String(value); - } - setReason(value: string | null | undefined) { - this.reason = value; - return this; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - #message?: string | null = undefined; - /** - * Human-readable explanation of the sub-error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - set message(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#message = correctType ? value : String(value); - } - setMessage(value: string | null | undefined) { - this.message = value; - return this; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - #messageTranslated?: string | null = undefined; - /** - * Localized/translated version of the sub-error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - set messageTranslated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#messageTranslated = correctType ? value : String(value); - } - setMessageTranslated(value: string | null | undefined) { - this.messageTranslated = value; - return this; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - #location?: string | null = undefined; - /** - * Field or parameter in which the error occurred. - * @returns {string} - **/ - get location() { - return this.#location; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - set location(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#location = correctType ? value : String(value); - } - setLocation(value: string | null | undefined) { - this.location = value; - return this; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - #locationType?: string | null = undefined; - /** - * Type of location (e.g., parameter, header). - * @returns {string} - **/ - get locationType() { - return this.#locationType; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - set locationType(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#locationType = correctType ? value : String(value); - } - setLocationType(value: string | null | undefined) { - this.locationType = value; - return this; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - #extendedHelp?: string | null = undefined; - /** - * URL linking to additional documentation about the error. - * @returns {string} - **/ - get extendedHelp() { - return this.#extendedHelp; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - set extendedHelp(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#extendedHelp = correctType ? value : String(value); - } - setExtendedHelp(value: string | null | undefined) { - this.extendedHelp = value; - return this; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - #sendReport?: string | null = undefined; - /** - * URL to submit a report for this error. - * @returns {string} - **/ - get sendReport() { - return this.#sendReport; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - set sendReport(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#sendReport = correctType ? value : String(value); - } - setSendReport(value: string | null | undefined) { - this.sendReport = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.domain !== undefined) { - this.domain = d.domain; - } - if (d.reason !== undefined) { - this.reason = d.reason; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.location !== undefined) { - this.location = d.location; - } - if (d.locationType !== undefined) { - this.locationType = d.locationType; - } - if (d.extendedHelp !== undefined) { - this.extendedHelp = d.extendedHelp; - } - if (d.sendReport !== undefined) { - this.sendReport = d.sendReport; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - domain: this.#domain, - reason: this.#reason, - message: this.#message, - messageTranslated: this.#messageTranslated, - location: this.#location, - locationType: this.#locationType, - extendedHelp: this.#extendedHelp, - sendReport: this.#sendReport, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - domain: "domain", - reason: "reason", - message: "message", - messageTranslated: "messageTranslated", - location: "location", - locationType: "locationType", - extendedHelp: "extendedHelp", - sendReport: "sendReport", - }; - } - /** - * Creates an instance of ResponseDto.Error.Errors, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType.ErrorsType) { - return new ResponseDto.Error.Errors(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error.Errors, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep, - ) { - return new ResponseDto.Error.Errors(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error.Errors({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error.Errors(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.code !== undefined) { - this.code = d.code; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.errors !== undefined) { - this.errors = d.errors; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - code: this.#code, - message: this.#message, - messageTranslated: this.#messageTranslated, - errors: this.#errors, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - code: "code", - message: "message", - messageTranslated: "messageTranslated", - errors$: "errors", - get errors() { - return withPrefix( - "error.errors[:i]", - ResponseDto.Error.Errors.Fields, - ); - }, - }; - } - /** - * Creates an instance of ResponseDto.Error, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType) { - return new ResponseDto.Error(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep) { - return new ResponseDto.Error(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - this.#lateInitFields(); - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.apiVersion !== undefined) { - this.apiVersion = d.apiVersion; - } - if (d.context !== undefined) { - this.context = d.context; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.method !== undefined) { - this.method = d.method; - } - if (d.params !== undefined) { - this.params = d.params; - } - if (d.data !== undefined) { - this.data = d.data; - } - if (d.error !== undefined) { - this.error = d.error; - } - this.#lateInitFields(data); - } - /** - * These are the class instances, which need to be initialised, regardless of the constructor incoming data - **/ - #lateInitFields(data = {}) { - const d = data as Partial>; - if (!(d.data instanceof ResponseDto.Data)) { - this.data = new ResponseDto.Data(d.data || {}); - } - if (!(d.error instanceof ResponseDto.Error)) { - this.error = new ResponseDto.Error(d.error || {}); - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - apiVersion: this.#apiVersion, - context: this.#context, - id: this.#id, - method: this.#method, - params: this.#params, - data: this.#data, - error: this.#error, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - apiVersion: "apiVersion", - context: "context", - id: "id", - method: "method", - params: "params", - data$: "data", - get data() { - return withPrefix("data", ResponseDto.Data.Fields); - }, - error$: "error", - get error() { - return withPrefix("error", ResponseDto.Error.Fields); - }, - }; - } - /** - * Creates an instance of ResponseDto, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType) { - return new ResponseDto(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep>) { - return new ResponseDto(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto(this.toJSON()); - } -} -export abstract class ResponseDtoFactory { - abstract create(data: unknown): ResponseDto; -} -type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; -/** - * The base type definition for responseDto - **/ -export type ResponseDtoType = { - /** - * Version of the API used for this response. - * @type {string} - **/ - apiVersion?: string; - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - context?: string; - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - id?: string; - /** - * Name of the API method invoked. - * @type {string} - **/ - method?: string; - /** - * Parameters sent with the request. - * @type {any} - **/ - params: any; - /** - * Main data payload of the response. - * @type {ResponseDtoType.DataType} - **/ - data: ResponseDtoType.DataType; - /** - * Error details, if the request failed. - * @type {ResponseDtoType.ErrorType} - **/ - error: ResponseDtoType.ErrorType; -}; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ResponseDtoType { - /** - * The base type definition for dataType - **/ - export type DataType = { - /** - * Single item returned by the API. - * @type {any} - **/ - item2: T; - /** - * List of items returned by the API. - * @type {any} - **/ - items: any; - /** - * Link to edit this resource. - * @type {string} - **/ - editLink?: string; - /** - * Link to retrieve this resource. - * @type {string} - **/ - selfLink?: string; - /** - * Resource type (kind) identifier. - * @type {string} - **/ - kind?: string; - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - fields?: string; - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - etag?: string; - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - cursor?: string; - /** - * Unique identifier of the resource. - * @type {string} - **/ - id?: string; - /** - * Language code of the response data. - * @type {string} - **/ - lang?: string; - /** - * Last modification time of the resource. - * @type {string} - **/ - updated?: string; - /** - * Number of items in the current response page. - * @type {number} - **/ - currentItemCount?: number; - /** - * Maximum number of items per page. - * @type {number} - **/ - itemsPerPage?: number; - /** - * Index of the first item in the current page. - * @type {number} - **/ - startIndex?: number; - /** - * Total number of items available. - * @type {number} - **/ - totalItems?: number; - /** - * Number of items available for this user/query. - * @type {number} - **/ - totalAvailableItems?: number; - /** - * Current page index in the pagination. - * @type {number} - **/ - pageIndex?: number; - /** - * Total number of pages in the pagination. - * @type {number} - **/ - totalPages?: number; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace DataType {} - /** - * The base type definition for errorType - **/ - export type ErrorType = { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - code: number; - /** - * Human-readable explanation of the error. - * @type {string} - **/ - message: string; - /** - * Localized/translated version of the error message. - * @type {string} - **/ - messageTranslated: string; - /** - * Detailed list of error objects. - * @type {ResponseDtoType.ErrorType.ErrorsType[]} - **/ - errors: ResponseDtoType.ErrorType.ErrorsType[]; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorType { - /** - * The base type definition for errorsType - **/ - export type ErrorsType = { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - domain?: string; - /** - * Reason identifier for the error. - * @type {string} - **/ - reason?: string; - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - message?: string; - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - messageTranslated?: string; - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - location?: string; - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - locationType?: string; - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - extendedHelp?: string; - /** - * URL to submit a report for this error. - * @type {string} - **/ - sendReport?: string; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorsType {} - } -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json deleted file mode 100644 index 7a3dc447..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "sdk", - "version": "1.0.0", - "description": "Auto-generated package.json", - "main": "index.js", - "scripts": { - "build": "echo 'build script here'", - "test": "echo 'test script here'" - }, - "dependencies": { - "@types/qs": "^6.14.0", - "qs": "^6.14.0" - } -} \ No newline at end of file diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml deleted file mode 100644 index 0dcb101c..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: googleEnvelop -description: - Generating envelop API responses using Emi itself. - Emi codegen is so strong that can generate deep classes in javascript which could be used - in itself and in this example we are doing it. - - All responses can be wrapped in google json styleguide, which gives extream consistency. - -dtos: - - name: response - fields: - - name: apiVersion - type: string? - description: Version of the API used for this response. - - name: context - type: string? - description: Context string provided by the client or system for request tracking. - - name: id - type: string? - description: Unique identifier assigned to the request/response. - - name: method - type: string? - description: Name of the API method invoked. - - name: params - type: any - description: Parameters sent with the request. - - name: data - type: object - description: Main data payload of the response. - fields: - - name: item - type: any - description: Single item returned by the API. - - name: items - type: any - description: List of items returned by the API. - - name: editLink - type: string? - description: Link to edit this resource. - - name: selfLink - type: string? - description: Link to retrieve this resource. - - name: kind - type: string? - description: Resource type (kind) identifier. - - name: fields - type: string? - description: Selector specifying which fields are included in a partial response. - - name: etag - type: string? - description: ETag of the resource, used for caching/version control. - - name: cursor - type: string? - description: Cursor for paginated data fetching. - - name: id - type: string? - description: Unique identifier of the resource. - - name: lang - type: string? - description: Language code of the response data. - - name: updated - type: string? - description: Last modification time of the resource. - - name: currentItemCount - type: int? - description: Number of items in the current response page. - - name: itemsPerPage - type: int? - description: Maximum number of items per page. - - name: startIndex - type: int? - description: Index of the first item in the current page. - - name: totalItems - type: int? - description: Total number of items available. - - name: totalAvailableItems - type: int? - description: Number of items available for this user/query. - - name: pageIndex - type: int? - description: Current page index in the pagination. - - name: totalPages - type: int? - description: Total number of pages in the pagination. - - name: error - type: object - description: Error details, if the request failed. - fields: - - name: code - type: int - description: Numeric error code representing the failure. - - name: message - type: string - description: Human-readable explanation of the error. - - name: messageTranslated - type: string - description: Localized/translated version of the error message. - - name: errors - type: array - description: Detailed list of error objects. - fields: - - name: domain - type: string? - description: Logical grouping of the error (e.g., global, usageLimits). - - name: reason - type: string? - description: Reason identifier for the error. - - name: message - type: string? - description: Human-readable explanation of the sub-error. - - name: messageTranslated - type: string? - description: Localized/translated version of the sub-error message. - - name: location - type: string? - description: Field or parameter in which the error occurred. - - name: locationType - type: string? - description: Type of location (e.g., parameter, header). - - name: extendedHelp - type: string? - description: URL linking to additional documentation about the error. - - name: sendReport - type: string? - description: URL to submit a report for this error. diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts deleted file mode 100644 index 2fc2601b..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; -import { ResponseDto } from "./generated/ResponseDto"; -// Use this class to generate a GResponse. -export class GResponse extends ResponseDto implements EnvelopeClass { - creator?: CreatorSignature | null; - constructor(data?: unknown) { - super(data); - } - setCreator(fn: CreatorSignature) { - this.creator = fn; - return this; - } - /** - * GResponse can have data.item or data.items - * We create that based on incoming data tpye, so there is no need for 2 different - * classes, one for array and other for singular - * @param data - * @returns - */ - inject(body: any): this { - this.applyFromObject(body); - if ((body as any)?.data) { - if (!this.data) { - this.setData({} as any); - } - if ( - Array.isArray(body?.data.items) && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItems( - body?.data?.items?.map((item: unknown) => this.creator?.(item)), - ); - } else if ( - typeof body?.data?.item === "object" && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItem(this.creator(body?.data?.item)); - } else { - this.data?.setItem(body?.data?.item); - } - } - return this; - } -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/index.ts b/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/index.ts deleted file mode 100644 index 63d3ef26..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-management/sdk/envelopes/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./google-json-style-guide/index"; -export * from "./flat-array/FlatArray"; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/GetOfferTranslationsAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-translations/GetOfferTranslationsAction.js index 3e3c7e14..991c43fa 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/GetOfferTranslationsAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-translations/GetOfferTranslationsAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -152,7 +145,7 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations} **/ - #translations = []; + #translations = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations} @@ -165,19 +158,38 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations} **/ set translations(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetOfferTranslationsActionRes.Translations + ) { + this.#translations = MArray.of(value); + } else { + this.#translations = MArray.of( + value.map( + (item) => new GetOfferTranslationsActionRes.Translations(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetOfferTranslationsActionRes.Translations - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#translations = value; - } else { - this.#translations = value.map( - (item) => new GetOfferTranslationsActionRes.Translations(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#translations = mcastValue; + return; } + console.warn( + "Cannot assing value to translations, because it needs MArray instance or an Array.", + ); } setTranslations(value) { this.translations = value; @@ -518,7 +530,7 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections} **/ - #sections = []; + #sections = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections} @@ -531,24 +543,43 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections} **/ set sections(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferTranslationsActionRes.Translations.Description + .Translation.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferTranslationsActionRes.Translations.Description.Translation - .Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue; + return; + } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections(value) { this.sections = value; @@ -562,7 +593,7 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items} @@ -575,24 +606,43 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferTranslationsActionRes.Translations.Description + .Translation.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferTranslationsActionRes.Translations.Description - .Translation.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; @@ -1033,7 +1083,7 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations.SafetyInformation.Products} **/ - #products = []; + #products = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations.SafetyInformation.Products} @@ -1046,24 +1096,43 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations.SafetyInformation.Products} **/ set products(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferTranslationsActionRes.Translations.SafetyInformation + .Products + ) { + this.#products = MArray.of(value); + } else { + this.#products = MArray.of( + value.map( + (item) => + new GetOfferTranslationsActionRes.Translations.SafetyInformation.Products( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferTranslationsActionRes.Translations.SafetyInformation - .Products - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#products = value; - } else { - this.#products = value.map( - (item) => - new GetOfferTranslationsActionRes.Translations.SafetyInformation.Products( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#products = mcastValue; + return; } + console.warn( + "Cannot assing value to products, because it needs MArray instance or an Array.", + ); } setProducts(value) { this.products = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/UpdateOfferTranslationAction.js b/examples/allegro-sdk/javascript/gen/offer/offer-translations/UpdateOfferTranslationAction.js index 0bd7daef..a728ac92 100644 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/UpdateOfferTranslationAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/offer-translations/UpdateOfferTranslationAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -244,7 +237,7 @@ export class UpdateOfferTranslationActionReq { * * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections} **/ - #sections = []; + #sections = MArray.of([]); /** * * @returns {UpdateOfferTranslationActionReq.Description.Translation.Sections} @@ -257,23 +250,42 @@ export class UpdateOfferTranslationActionReq { * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections} **/ set sections(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + UpdateOfferTranslationActionReq.Description.Translation.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new UpdateOfferTranslationActionReq.Description.Translation.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - UpdateOfferTranslationActionReq.Description.Translation.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new UpdateOfferTranslationActionReq.Description.Translation.Sections( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue; + return; } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections(value) { this.sections = value; @@ -287,7 +299,7 @@ export class UpdateOfferTranslationActionReq { * * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {UpdateOfferTranslationActionReq.Description.Translation.Sections.Items} @@ -300,24 +312,43 @@ export class UpdateOfferTranslationActionReq { * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + UpdateOfferTranslationActionReq.Description.Translation.Sections + .Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new UpdateOfferTranslationActionReq.Description.Translation.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - UpdateOfferTranslationActionReq.Description.Translation.Sections - .Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new UpdateOfferTranslationActionReq.Description.Translation.Sections.Items( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; @@ -856,7 +887,7 @@ export class UpdateOfferTranslationActionReq { * * @type {UpdateOfferTranslationActionReq.SafetyInformation.Products} **/ - #products = []; + #products = MArray.of([]); /** * * @returns {UpdateOfferTranslationActionReq.SafetyInformation.Products} @@ -869,23 +900,42 @@ export class UpdateOfferTranslationActionReq { * @type {UpdateOfferTranslationActionReq.SafetyInformation.Products} **/ set products(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + UpdateOfferTranslationActionReq.SafetyInformation.Products + ) { + this.#products = MArray.of(value); + } else { + this.#products = MArray.of( + value.map( + (item) => + new UpdateOfferTranslationActionReq.SafetyInformation.Products( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - UpdateOfferTranslationActionReq.SafetyInformation.Products - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#products = value; - } else { - this.#products = value.map( - (item) => - new UpdateOfferTranslationActionReq.SafetyInformation.Products( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#products = mcastValue; + return; + } + console.warn( + "Cannot assing value to products, because it needs MArray instance or an Array.", + ); } setProducts(value) { this.products = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/buildUrl.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/buildUrl.ts deleted file mode 100644 index cf08f1cc..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/buildUrl.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Handy tool to create a final callable url, from query string, query params, - * and the actual url. - * @param template - * @param params - * @param qs - * @returns - */ -export function buildUrl( - url: string, - params?: Record, - qs?: URLSearchParams -) { - // Replace :placeholders - if (params) { - Object.entries(params as Record).forEach(([key, value]) => { - url = url.replace( - new RegExp(`:${key}`, "g"), - encodeURIComponent(String(value)) - ); - }); - } - - if (qs && qs instanceof URLSearchParams) { - url += `?${qs.toString()}`; - } else if (qs && Object.keys(qs).length) { - const query = new URLSearchParams( - Object.entries(qs).map(([k, v]) => [k, String(v)]) - ).toString(); - url += `?${query}`; - } - - return url; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/fetchx.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/fetchx.ts deleted file mode 100644 index 774f16b0..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/fetchx.ts +++ /dev/null @@ -1,196 +0,0 @@ -export type TypedRequestInit = Omit< - RequestInit, - "body" | "headers" -> & { - body?: TBody; - headers?: THeaders; -}; -export class TypedResponse extends Response { - override json(): Promise { - return super.json(); - } - result: - | T - | undefined - | ReadableStream> - | null - | string; -} -export async function fetchx< - TResponse = unknown, - TBody = unknown, - THeaders = unknown, ->( - input: RequestInfo | URL, - init?: TypedRequestInit, - ctx?: FetchxContext | null, -): Promise> { - let url = input.toString(); - let reqInit: TypedRequestInit = init || {}; - let res: TypedResponse; - let fetchFn = fetch; - - if (ctx) { - [url, reqInit] = await ctx.apply(url, reqInit); - - if (ctx.fetchOverrideFn) { - fetchFn = ctx.fetchOverrideFn; - } - } - - res = (await fetchFn( - url, - reqInit as RequestInit, - )) as TypedResponse; - - if (ctx) { - res = await ctx.handle(res); - } - return res; -} -type DtoFactory = { new (data: any): T } | ((data: any) => T); -function isConstructor(fn: DtoFactory): fn is { new (data: any): T } { - return ( - typeof fn === "function" && fn.prototype && fn.prototype.constructor === fn - ); -} -export async function handleFetchResponse( - res: TypedResponse, - dto?: DtoFactory, - onMessage?: (msg: any) => void, - signal?: AbortSignal | null, -): Promise<{ done: Promise; response: TypedResponse }> { - const ct = res.headers.get("content-type") || ""; - const cd = res.headers.get("content-disposition") || ""; - if (ct.includes("text/event-stream")) { - return SSEFetch(res, onMessage, signal); - } - if ( - cd.includes("attachment") || - (!ct.includes("json") && !ct.startsWith("text/")) - ) { - (res as any).result = res.body; - } else if (ct.includes("application/json")) { - const json = await res.json(); - if (dto) { - if (isConstructor(dto)) { - (res as any).result = new dto(json); // ✅ class constructor - } else { - (res as any).result = dto(json); // ✅ factory function - } - } else { - (res as any).result = json; - } - } else { - (res as any).result = await res.text(); - } - return { done: Promise.resolve(), response: res as any }; -} -export const SSEFetch = ( - res: TypedResponse, - onMessage?: (ev: MessageEvent) => void, - signal?: AbortSignal | null, -): { response: TypedResponse; done: Promise } => { - if (!res.body) throw new Error("SSE requires readable body"); - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - const done = new Promise((resolve, reject) => { - function readChunk() { - reader - .read() - .then(({ done: finished, value }) => { - if (signal?.aborted) { - reader.cancel(); - return resolve(); // resolve on abort - } - if (finished) return resolve(); // normal end - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split("\n\n"); - buffer = parts.pop() || ""; - for (const part of parts) { - let data = ""; - let event = "message"; - part.split("\n").forEach((line) => { - if (line.startsWith("data:")) data += line.slice(5).trim(); - else if (line.startsWith("event:")) event = line.slice(6).trim(); - }); - if (data) { - if (data === "[DONE]") return resolve(); - onMessage?.(new MessageEvent(event, { data })); - } - } - readChunk(); - }) - .catch((err) => { - if (err.name === "AbortError") resolve(); - else reject(err); - }); - } - readChunk(); - }); - return { response: res, done }; -}; -export class FetchxContext { - constructor( - public baseUrl: string = "", - public defaultHeaders: Record = {}, - public requestInterceptor?: ( - url: string, - init: TypedRequestInit, - ) => - | Promise<[string, TypedRequestInit]> - | [string, TypedRequestInit], - public responseInterceptor?: ( - res: TypedResponse, - ) => Promise>, - /** - * Overrides the browser fetch function, for different purposes. It would recieve the same first 2 arguments as fetch, - * as well as third one of fetchx context. If you pass the fetch itself to override, it should have no effect. - */ - public fetchOverrideFn?: ( - input: RequestInfo | URL, - init?: TypedRequestInit, - ) => Promise, - ) {} - async apply( - url: string, - init: TypedRequestInit, - ): Promise<[string, TypedRequestInit]> { - // prefix baseUrl - if (!/^https?:\/\//.test(url)) { - url = this.baseUrl + url; - } - // merge default headers - (init.headers as unknown) = { - ...this.defaultHeaders, - ...((init.headers as object) || {}), - }; - // call request interceptor if present - if (this.requestInterceptor) { - return this.requestInterceptor(url, init); - } - return [url, init]; - } - async handle(res: TypedResponse): Promise> { - if (this.responseInterceptor) { - return this.responseInterceptor(res); - } - return res; - } - clone(overrides?: Partial): FetchxContext { - return new FetchxContext( - overrides?.baseUrl ?? this.baseUrl, - { ...this.defaultHeaders, ...(overrides?.defaultHeaders || {}) }, - overrides?.requestInterceptor ?? this.requestInterceptor, - overrides?.responseInterceptor ?? this.responseInterceptor, - ); - } -} -export type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; \ No newline at end of file diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/operators.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/operators.ts deleted file mode 100644 index 728da07e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/operators.ts +++ /dev/null @@ -1,173 +0,0 @@ -export class MOne { - private operation: string | null = null; - private selector: S | undefined; - - private content: T | undefined = undefined; - - isNull(): boolean { - return this.content === null; - } - - isSelector(): boolean { - return this.selector !== undefined && this.operation !== null; - } - - get(): T { - return this.content!; - } - - static of(value: T) { - const one = new MOne(); - one.content = value; - - return one; - } - - static select(selector: any) { - const one = new MOne(); - one.selector = selector; - one.operation = "replace"; - - return one; - } - - toJSON() { - // When its explicit replace, it means that we need to pass a selector, so reader will - // be able to replace it via internal mechanism - if (this.operation === "replace") { - return { - __operation: this.operation, - selector: this.selector, - }; - } - - return this.content; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, maybe just giving back one is enough. -export class MOneNullable extends MOne {} - -// Array describes how an incoming list should be applied to an existing one, -// mirroring emigo.Array on the Go side. It lets a PATCH-style payload say -// "replace the whole set" versus "append to the existing set". -// -// On the wire a "replace" is implicit (a bare array), while an "append" is -// tagged with __operation so the reader keeps the existing rows. This keeps -// the payload identical to the Go client/backend generators. -export class MArray { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "replace"; - - return arr; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "append"; - - return arr; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Array is enough. -export class MArrayNullable extends Array {} - -// Collection mirrors emigo.Collection on the Go side. Structurally it is the -// same as Array — a list carrying a "replace"/"append" operation — but it is a -// distinct field type: a collection holds a list of a target entity, whereas an -// array holds a list of an inline DTO. -export class MCollection { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "replace"; - - return collection; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "append"; - - return collection; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Collection is enough. -export class CollectionNullable extends MCollection {} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts deleted file mode 100644 index 850d7626..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * To declare a new envelope class, you must follow these rules: - * 1. The constructor must accept any object, which will contain the parsed JSON message - * from a response. - * 2. Envelope classes must provide a function to update the payload. Since payloads are - * type-safe, they must be instantiated and passed to the envelope; the common constructor - * alone is not enough. - * 3. Enveope must have a way to provide the content back actually, in order to create a class out of them. - */ - -export type CreatorSignature = (item: unknown) => T; - -export interface EnvelopeClass { - setCreator(fn: CreatorSignature): this; - inject(data: unknown): this; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts deleted file mode 100644 index 455cdd2e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; - -// Some responses are returning a flat array, without any other information -// regarding the pagination, etc. They start [{},{}...] style. -// For those which might have a single project which is array but none-standard, -// Use CaptureArray instead. - -export class FlatArray implements EnvelopeClass { - public data: T[] = []; - creator?: CreatorSignature | null = null; - - inject(data: unknown) { - if (!Array.isArray(data)) { - throw new Error( - "FlatArray can only work on flat array items, such as [{},...], and doesn't accept any other type" - ); - } - - if (typeof this.creator !== "undefined") { - this.data = data.map((item) => - (this.creator as CreatorSignature)(item) - ); - } else { - this.data = data; - } - - return this; - } - - setCreator(creator: CreatorSignature) { - this.creator = creator; - - return this; - } - - // Implement thigs here, which would make the flat array to act as an array actually, how can it become - // class instance as an array? -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts deleted file mode 100644 index 0c078ce3..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts +++ /dev/null @@ -1,1715 +0,0 @@ -import { withPrefix } from "./sdk/common/withPrefix"; -/** - * The base class definition for responseDto - **/ -export class ResponseDto { - /** - * Version of the API used for this response. - * @type {string} - **/ - #apiVersion?: string | null = undefined; - /** - * Version of the API used for this response. - * @returns {string} - **/ - get apiVersion() { - return this.#apiVersion; - } - /** - * Version of the API used for this response. - * @type {string} - **/ - set apiVersion(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#apiVersion = correctType ? value : String(value); - } - setApiVersion(value: string | null | undefined) { - this.apiVersion = value; - return this; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - #context?: string | null = undefined; - /** - * Context string provided by the client or system for request tracking. - * @returns {string} - **/ - get context() { - return this.#context; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - set context(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#context = correctType ? value : String(value); - } - setContext(value: string | null | undefined) { - this.context = value; - return this; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier assigned to the request/response. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - #method?: string | null = undefined; - /** - * Name of the API method invoked. - * @returns {string} - **/ - get method() { - return this.#method; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - set method(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#method = correctType ? value : String(value); - } - setMethod(value: string | null | undefined) { - this.method = value; - return this; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - #params: any = null; - /** - * Parameters sent with the request. - * @returns {any} - **/ - get params() { - return this.#params; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - set params(value: any) { - this.#params = value; - } - setParams(value: any) { - this.params = value; - return this; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - #data!: InstanceType>; - /** - * Main data payload of the response. - * @returns {ResponseDto.Data} - **/ - get data() { - return this.#data; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - set data(value: InstanceType>) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Data) { - this.#data = value; - } else { - this.#data = new ResponseDto.Data(value); - } - } - setData(value: InstanceType>) { - this.data = value; - return this; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - #error!: InstanceType; - /** - * Error details, if the request failed. - * @returns {ResponseDto.Error} - **/ - get error() { - return this.#error; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - set error(value: InstanceType) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Error) { - this.#error = value; - } else { - this.#error = new ResponseDto.Error(value); - } - } - setError(value: InstanceType) { - this.error = value; - return this; - } - /** - * The base class definition for data - **/ - static Data = class Data { - /** - * Single item returned by the API. - * @type {any} - **/ - #item: T | null = null; - /** - * Single item returned by the API. - * @returns {T} - **/ - get item(): T | null { - return this.#item; - } - /** - * Single item returned by the API. - * @type {any} - **/ - set item(value: any) { - this.#item = value; - } - setItem(value: any) { - this.item = value; - return this; - } - /** - * List of items returned by the API. - * @type {any} - **/ - #items: T[] = []; - /** - * List of items returned by the API. - * @returns {T[]} - **/ - get items(): T[] { - return this.#items; - } - /** - * List of items returned by the API. - * @type {T[]} - **/ - set items(value: T[]) { - this.#items = value; - } - setItems(value: T[]) { - this.items = value; - return this; - } - /** - * Link to edit this resource. - * @type {string} - **/ - #editLink?: string | null = undefined; - /** - * Link to edit this resource. - * @returns {string} - **/ - get editLink() { - return this.#editLink; - } - /** - * Link to edit this resource. - * @type {string} - **/ - set editLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#editLink = correctType ? value : String(value); - } - setEditLink(value: string | null | undefined) { - this.editLink = value; - return this; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - #selfLink?: string | null = undefined; - /** - * Link to retrieve this resource. - * @returns {string} - **/ - get selfLink() { - return this.#selfLink; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - set selfLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#selfLink = correctType ? value : String(value); - } - setSelfLink(value: string | null | undefined) { - this.selfLink = value; - return this; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - #kind?: string | null = undefined; - /** - * Resource type (kind) identifier. - * @returns {string} - **/ - get kind() { - return this.#kind; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - set kind(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#kind = correctType ? value : String(value); - } - setKind(value: string | null | undefined) { - this.kind = value; - return this; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - #fields?: string | null = undefined; - /** - * Selector specifying which fields are included in a partial response. - * @returns {string} - **/ - get fields() { - return this.#fields; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - set fields(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#fields = correctType ? value : String(value); - } - setFields(value: string | null | undefined) { - this.fields = value; - return this; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - #etag?: string | null = undefined; - /** - * ETag of the resource, used for caching/version control. - * @returns {string} - **/ - get etag() { - return this.#etag; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - set etag(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#etag = correctType ? value : String(value); - } - setEtag(value: string | null | undefined) { - this.etag = value; - return this; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - #cursor?: string | null = undefined; - /** - * Cursor for paginated data fetching. - * @returns {string} - **/ - get cursor() { - return this.#cursor; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - set cursor(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#cursor = correctType ? value : String(value); - } - setCursor(value: string | null | undefined) { - this.cursor = value; - return this; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier of the resource. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Language code of the response data. - * @type {string} - **/ - #lang?: string | null = undefined; - /** - * Language code of the response data. - * @returns {string} - **/ - get lang() { - return this.#lang; - } - /** - * Language code of the response data. - * @type {string} - **/ - set lang(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#lang = correctType ? value : String(value); - } - setLang(value: string | null | undefined) { - this.lang = value; - return this; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - #updated?: string | null = undefined; - /** - * Last modification time of the resource. - * @returns {string} - **/ - get updated() { - return this.#updated; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - set updated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#updated = correctType ? value : String(value); - } - setUpdated(value: string | null | undefined) { - this.updated = value; - return this; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - #currentItemCount?: number | null = undefined; - /** - * Number of items in the current response page. - * @returns {number} - **/ - get currentItemCount() { - return this.#currentItemCount; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - set currentItemCount(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#currentItemCount = parsedValue; - } - } - setCurrentItemCount(value: number | null | undefined) { - this.currentItemCount = value; - return this; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - #itemsPerPage?: number | null = undefined; - /** - * Maximum number of items per page. - * @returns {number} - **/ - get itemsPerPage() { - return this.#itemsPerPage; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - set itemsPerPage(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#itemsPerPage = parsedValue; - } - } - setItemsPerPage(value: number | null | undefined) { - this.itemsPerPage = value; - return this; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - #startIndex?: number | null = undefined; - /** - * Index of the first item in the current page. - * @returns {number} - **/ - get startIndex() { - return this.#startIndex; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - set startIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#startIndex = parsedValue; - } - } - setStartIndex(value: number | null | undefined) { - this.startIndex = value; - return this; - } - /** - * Total number of items available. - * @type {number} - **/ - #totalItems?: number | null = undefined; - /** - * Total number of items available. - * @returns {number} - **/ - get totalItems() { - return this.#totalItems; - } - /** - * Total number of items available. - * @type {number} - **/ - set totalItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalItems = parsedValue; - } - } - setTotalItems(value: number | null | undefined) { - this.totalItems = value; - return this; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - #totalAvailableItems?: number | null = undefined; - /** - * Number of items available for this user/query. - * @returns {number} - **/ - get totalAvailableItems() { - return this.#totalAvailableItems; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - set totalAvailableItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalAvailableItems = parsedValue; - } - } - setTotalAvailableItems(value: number | null | undefined) { - this.totalAvailableItems = value; - return this; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - #pageIndex?: number | null = undefined; - /** - * Current page index in the pagination. - * @returns {number} - **/ - get pageIndex() { - return this.#pageIndex; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - set pageIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#pageIndex = parsedValue; - } - } - setPageIndex(value: number | null | undefined) { - this.pageIndex = value; - return this; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - #totalPages?: number | null = undefined; - /** - * Total number of pages in the pagination. - * @returns {number} - **/ - get totalPages() { - return this.#totalPages; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - set totalPages(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalPages = parsedValue; - } - } - setTotalPages(value: number | null | undefined) { - this.totalPages = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.item !== undefined) { - this.item = d.item; - } - if (d.items !== undefined) { - this.items = d.items; - } - if (d.editLink !== undefined) { - this.editLink = d.editLink; - } - if (d.selfLink !== undefined) { - this.selfLink = d.selfLink; - } - if (d.kind !== undefined) { - this.kind = d.kind; - } - if (d.fields !== undefined) { - this.fields = d.fields; - } - if (d.etag !== undefined) { - this.etag = d.etag; - } - if (d.cursor !== undefined) { - this.cursor = d.cursor; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.lang !== undefined) { - this.lang = d.lang; - } - if (d.updated !== undefined) { - this.updated = d.updated; - } - if (d.currentItemCount !== undefined) { - this.currentItemCount = d.currentItemCount; - } - if (d.itemsPerPage !== undefined) { - this.itemsPerPage = d.itemsPerPage; - } - if (d.startIndex !== undefined) { - this.startIndex = d.startIndex; - } - if (d.totalItems !== undefined) { - this.totalItems = d.totalItems; - } - if (d.totalAvailableItems !== undefined) { - this.totalAvailableItems = d.totalAvailableItems; - } - if (d.pageIndex !== undefined) { - this.pageIndex = d.pageIndex; - } - if (d.totalPages !== undefined) { - this.totalPages = d.totalPages; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - item: this.#item, - items: this.#items, - editLink: this.#editLink, - selfLink: this.#selfLink, - kind: this.#kind, - fields: this.#fields, - etag: this.#etag, - cursor: this.#cursor, - id: this.#id, - lang: this.#lang, - updated: this.#updated, - currentItemCount: this.#currentItemCount, - itemsPerPage: this.#itemsPerPage, - startIndex: this.#startIndex, - totalItems: this.#totalItems, - totalAvailableItems: this.#totalAvailableItems, - pageIndex: this.#pageIndex, - totalPages: this.#totalPages, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - item: "item", - items: "items", - editLink: "editLink", - selfLink: "selfLink", - kind: "kind", - fields: "fields", - etag: "etag", - cursor: "cursor", - id: "id", - lang: "lang", - updated: "updated", - currentItemCount: "currentItemCount", - itemsPerPage: "itemsPerPage", - startIndex: "startIndex", - totalItems: "totalItems", - totalAvailableItems: "totalAvailableItems", - pageIndex: "pageIndex", - totalPages: "totalPages", - }; - } - /** - * Creates an instance of ResponseDto.Data, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.DataType) { - return new ResponseDto.Data(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Data, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep>, - ) { - return new ResponseDto.Data(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto.Data({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Data(this.toJSON()); - } - }; - /** - * The base class definition for error - **/ - static Error = class Error { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - #code: number = 0; - /** - * Numeric error code representing the failure. - * @returns {number} - **/ - get code() { - return this.#code; - } - /** - * Numeric error code representing the failure. - * @type {number} - **/ - set code(value: number) { - const correctType = typeof value === "number"; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#code = parsedValue; - } - } - setCode(value: number) { - this.code = value; - return this; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - #message: string = ""; - /** - * Human-readable explanation of the error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - set message(value: string) { - this.#message = String(value); - } - setMessage(value: string) { - this.message = value; - return this; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - #messageTranslated: string = ""; - /** - * Localized/translated version of the error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - set messageTranslated(value: string) { - this.#messageTranslated = String(value); - } - setMessageTranslated(value: string) { - this.messageTranslated = value; - return this; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - #errors: InstanceType[] = []; - /** - * Detailed list of error objects. - * @returns {ResponseDto.Error.Errors} - **/ - get errors() { - return this.#errors; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - set errors(value: InstanceType[]) { - // For arrays, you only can pass arrays to the object - if (!Array.isArray(value)) { - return; - } - if (value.length > 0 && value[0] instanceof ResponseDto.Error.Errors) { - this.#errors = value; - } else { - this.#errors = value.map((item) => new ResponseDto.Error.Errors(item)); - } - } - setErrors(value: InstanceType[]) { - this.errors = value; - return this; - } - /** - * The base class definition for errors - **/ - static Errors = class Errors { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - #domain?: string | null = undefined; - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @returns {string} - **/ - get domain() { - return this.#domain; - } - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - set domain(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#domain = correctType ? value : String(value); - } - setDomain(value: string | null | undefined) { - this.domain = value; - return this; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - #reason?: string | null = undefined; - /** - * Reason identifier for the error. - * @returns {string} - **/ - get reason() { - return this.#reason; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - set reason(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#reason = correctType ? value : String(value); - } - setReason(value: string | null | undefined) { - this.reason = value; - return this; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - #message?: string | null = undefined; - /** - * Human-readable explanation of the sub-error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - set message(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#message = correctType ? value : String(value); - } - setMessage(value: string | null | undefined) { - this.message = value; - return this; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - #messageTranslated?: string | null = undefined; - /** - * Localized/translated version of the sub-error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - set messageTranslated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#messageTranslated = correctType ? value : String(value); - } - setMessageTranslated(value: string | null | undefined) { - this.messageTranslated = value; - return this; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - #location?: string | null = undefined; - /** - * Field or parameter in which the error occurred. - * @returns {string} - **/ - get location() { - return this.#location; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - set location(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#location = correctType ? value : String(value); - } - setLocation(value: string | null | undefined) { - this.location = value; - return this; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - #locationType?: string | null = undefined; - /** - * Type of location (e.g., parameter, header). - * @returns {string} - **/ - get locationType() { - return this.#locationType; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - set locationType(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#locationType = correctType ? value : String(value); - } - setLocationType(value: string | null | undefined) { - this.locationType = value; - return this; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - #extendedHelp?: string | null = undefined; - /** - * URL linking to additional documentation about the error. - * @returns {string} - **/ - get extendedHelp() { - return this.#extendedHelp; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - set extendedHelp(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#extendedHelp = correctType ? value : String(value); - } - setExtendedHelp(value: string | null | undefined) { - this.extendedHelp = value; - return this; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - #sendReport?: string | null = undefined; - /** - * URL to submit a report for this error. - * @returns {string} - **/ - get sendReport() { - return this.#sendReport; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - set sendReport(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#sendReport = correctType ? value : String(value); - } - setSendReport(value: string | null | undefined) { - this.sendReport = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.domain !== undefined) { - this.domain = d.domain; - } - if (d.reason !== undefined) { - this.reason = d.reason; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.location !== undefined) { - this.location = d.location; - } - if (d.locationType !== undefined) { - this.locationType = d.locationType; - } - if (d.extendedHelp !== undefined) { - this.extendedHelp = d.extendedHelp; - } - if (d.sendReport !== undefined) { - this.sendReport = d.sendReport; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - domain: this.#domain, - reason: this.#reason, - message: this.#message, - messageTranslated: this.#messageTranslated, - location: this.#location, - locationType: this.#locationType, - extendedHelp: this.#extendedHelp, - sendReport: this.#sendReport, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - domain: "domain", - reason: "reason", - message: "message", - messageTranslated: "messageTranslated", - location: "location", - locationType: "locationType", - extendedHelp: "extendedHelp", - sendReport: "sendReport", - }; - } - /** - * Creates an instance of ResponseDto.Error.Errors, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType.ErrorsType) { - return new ResponseDto.Error.Errors(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error.Errors, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep, - ) { - return new ResponseDto.Error.Errors(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error.Errors({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error.Errors(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.code !== undefined) { - this.code = d.code; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.errors !== undefined) { - this.errors = d.errors; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - code: this.#code, - message: this.#message, - messageTranslated: this.#messageTranslated, - errors: this.#errors, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - code: "code", - message: "message", - messageTranslated: "messageTranslated", - errors$: "errors", - get errors() { - return withPrefix( - "error.errors[:i]", - ResponseDto.Error.Errors.Fields, - ); - }, - }; - } - /** - * Creates an instance of ResponseDto.Error, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType) { - return new ResponseDto.Error(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep) { - return new ResponseDto.Error(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - this.#lateInitFields(); - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.apiVersion !== undefined) { - this.apiVersion = d.apiVersion; - } - if (d.context !== undefined) { - this.context = d.context; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.method !== undefined) { - this.method = d.method; - } - if (d.params !== undefined) { - this.params = d.params; - } - if (d.data !== undefined) { - this.data = d.data; - } - if (d.error !== undefined) { - this.error = d.error; - } - this.#lateInitFields(data); - } - /** - * These are the class instances, which need to be initialised, regardless of the constructor incoming data - **/ - #lateInitFields(data = {}) { - const d = data as Partial>; - if (!(d.data instanceof ResponseDto.Data)) { - this.data = new ResponseDto.Data(d.data || {}); - } - if (!(d.error instanceof ResponseDto.Error)) { - this.error = new ResponseDto.Error(d.error || {}); - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - apiVersion: this.#apiVersion, - context: this.#context, - id: this.#id, - method: this.#method, - params: this.#params, - data: this.#data, - error: this.#error, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - apiVersion: "apiVersion", - context: "context", - id: "id", - method: "method", - params: "params", - data$: "data", - get data() { - return withPrefix("data", ResponseDto.Data.Fields); - }, - error$: "error", - get error() { - return withPrefix("error", ResponseDto.Error.Fields); - }, - }; - } - /** - * Creates an instance of ResponseDto, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType) { - return new ResponseDto(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep>) { - return new ResponseDto(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto(this.toJSON()); - } -} -export abstract class ResponseDtoFactory { - abstract create(data: unknown): ResponseDto; -} -type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; -/** - * The base type definition for responseDto - **/ -export type ResponseDtoType = { - /** - * Version of the API used for this response. - * @type {string} - **/ - apiVersion?: string; - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - context?: string; - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - id?: string; - /** - * Name of the API method invoked. - * @type {string} - **/ - method?: string; - /** - * Parameters sent with the request. - * @type {any} - **/ - params: any; - /** - * Main data payload of the response. - * @type {ResponseDtoType.DataType} - **/ - data: ResponseDtoType.DataType; - /** - * Error details, if the request failed. - * @type {ResponseDtoType.ErrorType} - **/ - error: ResponseDtoType.ErrorType; -}; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ResponseDtoType { - /** - * The base type definition for dataType - **/ - export type DataType = { - /** - * Single item returned by the API. - * @type {any} - **/ - item2: T; - /** - * List of items returned by the API. - * @type {any} - **/ - items: any; - /** - * Link to edit this resource. - * @type {string} - **/ - editLink?: string; - /** - * Link to retrieve this resource. - * @type {string} - **/ - selfLink?: string; - /** - * Resource type (kind) identifier. - * @type {string} - **/ - kind?: string; - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - fields?: string; - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - etag?: string; - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - cursor?: string; - /** - * Unique identifier of the resource. - * @type {string} - **/ - id?: string; - /** - * Language code of the response data. - * @type {string} - **/ - lang?: string; - /** - * Last modification time of the resource. - * @type {string} - **/ - updated?: string; - /** - * Number of items in the current response page. - * @type {number} - **/ - currentItemCount?: number; - /** - * Maximum number of items per page. - * @type {number} - **/ - itemsPerPage?: number; - /** - * Index of the first item in the current page. - * @type {number} - **/ - startIndex?: number; - /** - * Total number of items available. - * @type {number} - **/ - totalItems?: number; - /** - * Number of items available for this user/query. - * @type {number} - **/ - totalAvailableItems?: number; - /** - * Current page index in the pagination. - * @type {number} - **/ - pageIndex?: number; - /** - * Total number of pages in the pagination. - * @type {number} - **/ - totalPages?: number; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace DataType {} - /** - * The base type definition for errorType - **/ - export type ErrorType = { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - code: number; - /** - * Human-readable explanation of the error. - * @type {string} - **/ - message: string; - /** - * Localized/translated version of the error message. - * @type {string} - **/ - messageTranslated: string; - /** - * Detailed list of error objects. - * @type {ResponseDtoType.ErrorType.ErrorsType[]} - **/ - errors: ResponseDtoType.ErrorType.ErrorsType[]; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorType { - /** - * The base type definition for errorsType - **/ - export type ErrorsType = { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - domain?: string; - /** - * Reason identifier for the error. - * @type {string} - **/ - reason?: string; - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - message?: string; - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - messageTranslated?: string; - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - location?: string; - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - locationType?: string; - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - extendedHelp?: string; - /** - * URL to submit a report for this error. - * @type {string} - **/ - sendReport?: string; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorsType {} - } -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json deleted file mode 100644 index 7a3dc447..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "sdk", - "version": "1.0.0", - "description": "Auto-generated package.json", - "main": "index.js", - "scripts": { - "build": "echo 'build script here'", - "test": "echo 'test script here'" - }, - "dependencies": { - "@types/qs": "^6.14.0", - "qs": "^6.14.0" - } -} \ No newline at end of file diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml deleted file mode 100644 index 0dcb101c..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: googleEnvelop -description: - Generating envelop API responses using Emi itself. - Emi codegen is so strong that can generate deep classes in javascript which could be used - in itself and in this example we are doing it. - - All responses can be wrapped in google json styleguide, which gives extream consistency. - -dtos: - - name: response - fields: - - name: apiVersion - type: string? - description: Version of the API used for this response. - - name: context - type: string? - description: Context string provided by the client or system for request tracking. - - name: id - type: string? - description: Unique identifier assigned to the request/response. - - name: method - type: string? - description: Name of the API method invoked. - - name: params - type: any - description: Parameters sent with the request. - - name: data - type: object - description: Main data payload of the response. - fields: - - name: item - type: any - description: Single item returned by the API. - - name: items - type: any - description: List of items returned by the API. - - name: editLink - type: string? - description: Link to edit this resource. - - name: selfLink - type: string? - description: Link to retrieve this resource. - - name: kind - type: string? - description: Resource type (kind) identifier. - - name: fields - type: string? - description: Selector specifying which fields are included in a partial response. - - name: etag - type: string? - description: ETag of the resource, used for caching/version control. - - name: cursor - type: string? - description: Cursor for paginated data fetching. - - name: id - type: string? - description: Unique identifier of the resource. - - name: lang - type: string? - description: Language code of the response data. - - name: updated - type: string? - description: Last modification time of the resource. - - name: currentItemCount - type: int? - description: Number of items in the current response page. - - name: itemsPerPage - type: int? - description: Maximum number of items per page. - - name: startIndex - type: int? - description: Index of the first item in the current page. - - name: totalItems - type: int? - description: Total number of items available. - - name: totalAvailableItems - type: int? - description: Number of items available for this user/query. - - name: pageIndex - type: int? - description: Current page index in the pagination. - - name: totalPages - type: int? - description: Total number of pages in the pagination. - - name: error - type: object - description: Error details, if the request failed. - fields: - - name: code - type: int - description: Numeric error code representing the failure. - - name: message - type: string - description: Human-readable explanation of the error. - - name: messageTranslated - type: string - description: Localized/translated version of the error message. - - name: errors - type: array - description: Detailed list of error objects. - fields: - - name: domain - type: string? - description: Logical grouping of the error (e.g., global, usageLimits). - - name: reason - type: string? - description: Reason identifier for the error. - - name: message - type: string? - description: Human-readable explanation of the sub-error. - - name: messageTranslated - type: string? - description: Localized/translated version of the sub-error message. - - name: location - type: string? - description: Field or parameter in which the error occurred. - - name: locationType - type: string? - description: Type of location (e.g., parameter, header). - - name: extendedHelp - type: string? - description: URL linking to additional documentation about the error. - - name: sendReport - type: string? - description: URL to submit a report for this error. diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts deleted file mode 100644 index 2fc2601b..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; -import { ResponseDto } from "./generated/ResponseDto"; -// Use this class to generate a GResponse. -export class GResponse extends ResponseDto implements EnvelopeClass { - creator?: CreatorSignature | null; - constructor(data?: unknown) { - super(data); - } - setCreator(fn: CreatorSignature) { - this.creator = fn; - return this; - } - /** - * GResponse can have data.item or data.items - * We create that based on incoming data tpye, so there is no need for 2 different - * classes, one for array and other for singular - * @param data - * @returns - */ - inject(body: any): this { - this.applyFromObject(body); - if ((body as any)?.data) { - if (!this.data) { - this.setData({} as any); - } - if ( - Array.isArray(body?.data.items) && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItems( - body?.data?.items?.map((item: unknown) => this.creator?.(item)), - ); - } else if ( - typeof body?.data?.item === "object" && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItem(this.creator(body?.data?.item)); - } else { - this.data?.setItem(body?.data?.item); - } - } - return this; - } -} diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/index.ts b/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/index.ts deleted file mode 100644 index 63d3ef26..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/envelopes/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./google-json-style-guide/index"; -export * from "./flat-array/FlatArray"; diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.js b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.js index 7fdadc66..2f2df879 100644 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -1196,7 +1189,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet} **/ - #productSet = []; + #productSet = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet} @@ -1209,21 +1202,42 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet} **/ set productSet(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue; + return; + } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } setProductSet(value) { this.productSet = value; @@ -1233,7 +1247,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Attachments} **/ - #attachments = []; + #attachments = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Attachments} @@ -1246,21 +1260,42 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Attachments} **/ set attachments(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Attachments( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Attachments(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue; + return; + } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments(value) { this.attachments = value; @@ -2177,7 +2212,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional} **/ - #additional = []; + #additional = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional} @@ -2190,24 +2225,43 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional} **/ set additional(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Publication + .Marketplaces.Additional + ) { + this.#additional = MArray.of(value); + } else { + this.#additional = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Publication - .Marketplaces.Additional - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additional = value; - } else { - this.#additional = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additional = mcastValue; + return; + } + console.warn( + "Cannot assing value to additional, because it needs MArray instance or an Array.", + ); } setAdditional(value) { this.additional = value; @@ -4805,7 +4859,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections} **/ - #sections = []; + #sections = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections} @@ -4818,23 +4872,42 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections} **/ set sections(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue; + return; } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections(value) { this.sections = value; @@ -4848,7 +4921,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items} **/ - #items = []; + #items = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items} @@ -4861,24 +4934,43 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items} **/ set items(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Description + .Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Description.Sections - .Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems(value) { this.items = value; @@ -5394,7 +5486,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits} **/ - #deposits = []; + #deposits = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits} @@ -5407,23 +5499,42 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits} **/ set deposits(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue; + return; + } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits(value) { this.deposits = value; @@ -5637,7 +5748,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters} **/ - #parameters = []; + #parameters = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters} @@ -5650,24 +5761,43 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters} **/ set parameters(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product + .Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product - .Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters(value) { this.parameters = value; @@ -5877,7 +6007,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values} **/ - #values = []; + #values = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values} @@ -5890,24 +6020,43 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values} **/ set values(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet + .Product.Parameters.Values + ) { + this.#values = MArray.of(value); + } else { + this.#values = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product - .Parameters.Values - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#values = value; - } else { - this.#values = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#values = mcastValue; + return; + } + console.warn( + "Cannot assing value to values, because it needs MArray instance or an Array.", + ); } setValues(value) { this.values = value; @@ -5917,7 +6066,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds} **/ - #valuesIds = []; + #valuesIds = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds} @@ -5930,24 +6079,43 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds} **/ set valuesIds(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet + .Product.Parameters.ValuesIds + ) { + this.#valuesIds = MArray.of(value); + } else { + this.#valuesIds = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product - .Parameters.ValuesIds - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#valuesIds = value; - } else { - this.#valuesIds = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#valuesIds = mcastValue; + return; } + console.warn( + "Cannot assing value to valuesIds, because it needs MArray instance or an Array.", + ); } setValuesIds(value) { this.valuesIds = value; @@ -7910,7 +8078,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors} **/ - #errors = []; + #errors = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors} @@ -7923,23 +8091,42 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors} **/ set errors(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue; + return; } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors(value) { this.errors = value; @@ -7949,7 +8136,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings} **/ - #warnings = []; + #warnings = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings} @@ -7962,23 +8149,42 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings} **/ set warnings(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings + ) { + this.#warnings = MArray.of(value); + } else { + this.#warnings = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#warnings = value; - } else { - this.#warnings = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#warnings = mcastValue; + return; } + console.warn( + "Cannot assing value to warnings, because it needs MArray instance or an Array.", + ); } setWarnings(value) { this.warnings = value; @@ -9201,7 +9407,7 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates} **/ - #rates = []; + #rates = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates} @@ -9214,23 +9420,42 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates} **/ set rates(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue; + return; } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates(value) { this.rates = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.js b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.js index 79c8965d..fafd25ed 100644 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -117,7 +110,7 @@ export class GetEventsAboutTheSellerSOffersActionRes { * List of events related to offer state changes * @type {GetEventsAboutTheSellerSOffersActionRes.OfferEvents} **/ - #offerEvents = []; + #offerEvents = MArray.of([]); /** * List of events related to offer state changes * @returns {GetEventsAboutTheSellerSOffersActionRes.OfferEvents} @@ -130,19 +123,39 @@ export class GetEventsAboutTheSellerSOffersActionRes { * @type {GetEventsAboutTheSellerSOffersActionRes.OfferEvents} **/ set offerEvents(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetEventsAboutTheSellerSOffersActionRes.OfferEvents + ) { + this.#offerEvents = MArray.of(value); + } else { + this.#offerEvents = MArray.of( + value.map( + (item) => + new GetEventsAboutTheSellerSOffersActionRes.OfferEvents(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetEventsAboutTheSellerSOffersActionRes.OfferEvents - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offerEvents = value; - } else { - this.#offerEvents = value.map( - (item) => new GetEventsAboutTheSellerSOffersActionRes.OfferEvents(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offerEvents = mcastValue; + return; + } + console.warn( + "Cannot assing value to offerEvents, because it needs MArray instance or an Array.", + ); } setOfferEvents(value) { this.offerEvents = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.js b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.js index 1fce98c8..202a8ba2 100644 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.js @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSellersOffersAction.js b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSellersOffersAction.js index 69c3f732..5060037d 100644 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSellersOffersAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSellersOffersAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -506,7 +499,7 @@ export class GetSellersOffersActionRes { * * @type {GetSellersOffersActionRes.Offers} **/ - #offers = []; + #offers = MArray.of([]); /** * * @returns {GetSellersOffersActionRes.Offers} @@ -519,19 +512,36 @@ export class GetSellersOffersActionRes { * @type {GetSellersOffersActionRes.Offers} **/ set offers(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetSellersOffersActionRes.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map((item) => new GetSellersOffersActionRes.Offers(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetSellersOffersActionRes.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => new GetSellersOffersActionRes.Offers(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue; + return; } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } setOffers(value) { this.offers = value; @@ -3063,7 +3073,7 @@ export class GetSellersOffersActionRes { * * @type {GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional} **/ - #additional = []; + #additional = MArray.of([]); /** * * @returns {GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional} @@ -3076,24 +3086,43 @@ export class GetSellersOffersActionRes { * @type {GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional} **/ set additional(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSellersOffersActionRes.Offers.Publication.Marketplaces + .Additional + ) { + this.#additional = MArray.of(value); + } else { + this.#additional = MArray.of( + value.map( + (item) => + new GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSellersOffersActionRes.Offers.Publication.Marketplaces - .Additional - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additional = value; - } else { - this.#additional = value.map( - (item) => - new GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additional = mcastValue; + return; + } + console.warn( + "Cannot assing value to additional, because it needs MArray instance or an Array.", + ); } setAdditional(value) { this.additional = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.js b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.js index c5a9edec..27b7aec6 100644 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.js +++ b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx"; import { withPrefix } from "./sdk/common/withPrefix"; @@ -224,7 +217,7 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * List of smart delivery method identifiers * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods} **/ - #smartDeliveryMethods = []; + #smartDeliveryMethods = MArray.of([]); /** * List of smart delivery method identifiers * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods} @@ -237,23 +230,42 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods} **/ set smartDeliveryMethods(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods + ) { + this.#smartDeliveryMethods = MArray.of(value); + } else { + this.#smartDeliveryMethods = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#smartDeliveryMethods = value; - } else { - this.#smartDeliveryMethods = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#smartDeliveryMethods = mcastValue; + return; + } + console.warn( + "Cannot assing value to smartDeliveryMethods, because it needs MArray instance or an Array.", + ); } setSmartDeliveryMethods(value) { this.smartDeliveryMethods = value; @@ -263,7 +275,7 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * List of classification conditions with delivery method checks * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions} **/ - #conditions = []; + #conditions = MArray.of([]); /** * List of classification conditions with delivery method checks * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions} @@ -276,23 +288,42 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions} **/ set conditions(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + ) { + this.#conditions = MArray.of(value); + } else { + this.#conditions = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#conditions = value; - } else { - this.#conditions = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#conditions = mcastValue; + return; } + console.warn( + "Cannot assing value to conditions, because it needs MArray instance or an Array.", + ); } setConditions(value) { this.conditions = value; @@ -656,7 +687,7 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * Delivery methods that passed validation for this condition * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods} **/ - #passedDeliveryMethods = []; + #passedDeliveryMethods = MArray.of([]); /** * Delivery methods that passed validation for this condition * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods} @@ -669,24 +700,43 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods} **/ set passedDeliveryMethods(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + .PassedDeliveryMethods + ) { + this.#passedDeliveryMethods = MArray.of(value); + } else { + this.#passedDeliveryMethods = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - .PassedDeliveryMethods - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#passedDeliveryMethods = value; - } else { - this.#passedDeliveryMethods = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#passedDeliveryMethods = mcastValue; + return; } + console.warn( + "Cannot assing value to passedDeliveryMethods, because it needs MArray instance or an Array.", + ); } setPassedDeliveryMethods(value) { this.passedDeliveryMethods = value; @@ -696,7 +746,7 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * Delivery methods that failed validation for this condition * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods} **/ - #failedDeliveryMethods = []; + #failedDeliveryMethods = MArray.of([]); /** * Delivery methods that failed validation for this condition * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods} @@ -709,24 +759,43 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods} **/ set failedDeliveryMethods(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + .FailedDeliveryMethods + ) { + this.#failedDeliveryMethods = MArray.of(value); + } else { + this.#failedDeliveryMethods = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - .FailedDeliveryMethods - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#failedDeliveryMethods = value; - } else { - this.#failedDeliveryMethods = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#failedDeliveryMethods = mcastValue; + return; } + console.warn( + "Cannot assing value to failedDeliveryMethods, because it needs MArray instance or an Array.", + ); } setFailedDeliveryMethods(value) { this.failedDeliveryMethods = value; diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/buildUrl.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/buildUrl.ts deleted file mode 100644 index cf08f1cc..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/buildUrl.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Handy tool to create a final callable url, from query string, query params, - * and the actual url. - * @param template - * @param params - * @param qs - * @returns - */ -export function buildUrl( - url: string, - params?: Record, - qs?: URLSearchParams -) { - // Replace :placeholders - if (params) { - Object.entries(params as Record).forEach(([key, value]) => { - url = url.replace( - new RegExp(`:${key}`, "g"), - encodeURIComponent(String(value)) - ); - }); - } - - if (qs && qs instanceof URLSearchParams) { - url += `?${qs.toString()}`; - } else if (qs && Object.keys(qs).length) { - const query = new URLSearchParams( - Object.entries(qs).map(([k, v]) => [k, String(v)]) - ).toString(); - url += `?${query}`; - } - - return url; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/fetchx.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/fetchx.ts deleted file mode 100644 index 774f16b0..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/fetchx.ts +++ /dev/null @@ -1,196 +0,0 @@ -export type TypedRequestInit = Omit< - RequestInit, - "body" | "headers" -> & { - body?: TBody; - headers?: THeaders; -}; -export class TypedResponse extends Response { - override json(): Promise { - return super.json(); - } - result: - | T - | undefined - | ReadableStream> - | null - | string; -} -export async function fetchx< - TResponse = unknown, - TBody = unknown, - THeaders = unknown, ->( - input: RequestInfo | URL, - init?: TypedRequestInit, - ctx?: FetchxContext | null, -): Promise> { - let url = input.toString(); - let reqInit: TypedRequestInit = init || {}; - let res: TypedResponse; - let fetchFn = fetch; - - if (ctx) { - [url, reqInit] = await ctx.apply(url, reqInit); - - if (ctx.fetchOverrideFn) { - fetchFn = ctx.fetchOverrideFn; - } - } - - res = (await fetchFn( - url, - reqInit as RequestInit, - )) as TypedResponse; - - if (ctx) { - res = await ctx.handle(res); - } - return res; -} -type DtoFactory = { new (data: any): T } | ((data: any) => T); -function isConstructor(fn: DtoFactory): fn is { new (data: any): T } { - return ( - typeof fn === "function" && fn.prototype && fn.prototype.constructor === fn - ); -} -export async function handleFetchResponse( - res: TypedResponse, - dto?: DtoFactory, - onMessage?: (msg: any) => void, - signal?: AbortSignal | null, -): Promise<{ done: Promise; response: TypedResponse }> { - const ct = res.headers.get("content-type") || ""; - const cd = res.headers.get("content-disposition") || ""; - if (ct.includes("text/event-stream")) { - return SSEFetch(res, onMessage, signal); - } - if ( - cd.includes("attachment") || - (!ct.includes("json") && !ct.startsWith("text/")) - ) { - (res as any).result = res.body; - } else if (ct.includes("application/json")) { - const json = await res.json(); - if (dto) { - if (isConstructor(dto)) { - (res as any).result = new dto(json); // ✅ class constructor - } else { - (res as any).result = dto(json); // ✅ factory function - } - } else { - (res as any).result = json; - } - } else { - (res as any).result = await res.text(); - } - return { done: Promise.resolve(), response: res as any }; -} -export const SSEFetch = ( - res: TypedResponse, - onMessage?: (ev: MessageEvent) => void, - signal?: AbortSignal | null, -): { response: TypedResponse; done: Promise } => { - if (!res.body) throw new Error("SSE requires readable body"); - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - const done = new Promise((resolve, reject) => { - function readChunk() { - reader - .read() - .then(({ done: finished, value }) => { - if (signal?.aborted) { - reader.cancel(); - return resolve(); // resolve on abort - } - if (finished) return resolve(); // normal end - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split("\n\n"); - buffer = parts.pop() || ""; - for (const part of parts) { - let data = ""; - let event = "message"; - part.split("\n").forEach((line) => { - if (line.startsWith("data:")) data += line.slice(5).trim(); - else if (line.startsWith("event:")) event = line.slice(6).trim(); - }); - if (data) { - if (data === "[DONE]") return resolve(); - onMessage?.(new MessageEvent(event, { data })); - } - } - readChunk(); - }) - .catch((err) => { - if (err.name === "AbortError") resolve(); - else reject(err); - }); - } - readChunk(); - }); - return { response: res, done }; -}; -export class FetchxContext { - constructor( - public baseUrl: string = "", - public defaultHeaders: Record = {}, - public requestInterceptor?: ( - url: string, - init: TypedRequestInit, - ) => - | Promise<[string, TypedRequestInit]> - | [string, TypedRequestInit], - public responseInterceptor?: ( - res: TypedResponse, - ) => Promise>, - /** - * Overrides the browser fetch function, for different purposes. It would recieve the same first 2 arguments as fetch, - * as well as third one of fetchx context. If you pass the fetch itself to override, it should have no effect. - */ - public fetchOverrideFn?: ( - input: RequestInfo | URL, - init?: TypedRequestInit, - ) => Promise, - ) {} - async apply( - url: string, - init: TypedRequestInit, - ): Promise<[string, TypedRequestInit]> { - // prefix baseUrl - if (!/^https?:\/\//.test(url)) { - url = this.baseUrl + url; - } - // merge default headers - (init.headers as unknown) = { - ...this.defaultHeaders, - ...((init.headers as object) || {}), - }; - // call request interceptor if present - if (this.requestInterceptor) { - return this.requestInterceptor(url, init); - } - return [url, init]; - } - async handle(res: TypedResponse): Promise> { - if (this.responseInterceptor) { - return this.responseInterceptor(res); - } - return res; - } - clone(overrides?: Partial): FetchxContext { - return new FetchxContext( - overrides?.baseUrl ?? this.baseUrl, - { ...this.defaultHeaders, ...(overrides?.defaultHeaders || {}) }, - overrides?.requestInterceptor ?? this.requestInterceptor, - overrides?.responseInterceptor ?? this.responseInterceptor, - ); - } -} -export type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; \ No newline at end of file diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/operators.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/operators.ts deleted file mode 100644 index 728da07e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/operators.ts +++ /dev/null @@ -1,173 +0,0 @@ -export class MOne { - private operation: string | null = null; - private selector: S | undefined; - - private content: T | undefined = undefined; - - isNull(): boolean { - return this.content === null; - } - - isSelector(): boolean { - return this.selector !== undefined && this.operation !== null; - } - - get(): T { - return this.content!; - } - - static of(value: T) { - const one = new MOne(); - one.content = value; - - return one; - } - - static select(selector: any) { - const one = new MOne(); - one.selector = selector; - one.operation = "replace"; - - return one; - } - - toJSON() { - // When its explicit replace, it means that we need to pass a selector, so reader will - // be able to replace it via internal mechanism - if (this.operation === "replace") { - return { - __operation: this.operation, - selector: this.selector, - }; - } - - return this.content; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, maybe just giving back one is enough. -export class MOneNullable extends MOne {} - -// Array describes how an incoming list should be applied to an existing one, -// mirroring emigo.Array on the Go side. It lets a PATCH-style payload say -// "replace the whole set" versus "append to the existing set". -// -// On the wire a "replace" is implicit (a bare array), while an "append" is -// tagged with __operation so the reader keeps the existing rows. This keeps -// the payload identical to the Go client/backend generators. -export class MArray { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "replace"; - - return arr; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "append"; - - return arr; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Array is enough. -export class MArrayNullable extends Array {} - -// Collection mirrors emigo.Collection on the Go side. Structurally it is the -// same as Array — a list carrying a "replace"/"append" operation — but it is a -// distinct field type: a collection holds a list of a target entity, whereas an -// array holds a list of an inline DTO. -export class MCollection { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "replace"; - - return collection; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "append"; - - return collection; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Collection is enough. -export class CollectionNullable extends MCollection {} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/withPrefix.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts deleted file mode 100644 index 850d7626..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * To declare a new envelope class, you must follow these rules: - * 1. The constructor must accept any object, which will contain the parsed JSON message - * from a response. - * 2. Envelope classes must provide a function to update the payload. Since payloads are - * type-safe, they must be instantiated and passed to the envelope; the common constructor - * alone is not enough. - * 3. Enveope must have a way to provide the content back actually, in order to create a class out of them. - */ - -export type CreatorSignature = (item: unknown) => T; - -export interface EnvelopeClass { - setCreator(fn: CreatorSignature): this; - inject(data: unknown): this; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts deleted file mode 100644 index 455cdd2e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; - -// Some responses are returning a flat array, without any other information -// regarding the pagination, etc. They start [{},{}...] style. -// For those which might have a single project which is array but none-standard, -// Use CaptureArray instead. - -export class FlatArray implements EnvelopeClass { - public data: T[] = []; - creator?: CreatorSignature | null = null; - - inject(data: unknown) { - if (!Array.isArray(data)) { - throw new Error( - "FlatArray can only work on flat array items, such as [{},...], and doesn't accept any other type" - ); - } - - if (typeof this.creator !== "undefined") { - this.data = data.map((item) => - (this.creator as CreatorSignature)(item) - ); - } else { - this.data = data; - } - - return this; - } - - setCreator(creator: CreatorSignature) { - this.creator = creator; - - return this; - } - - // Implement thigs here, which would make the flat array to act as an array actually, how can it become - // class instance as an array? -} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts deleted file mode 100644 index 0c078ce3..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts +++ /dev/null @@ -1,1715 +0,0 @@ -import { withPrefix } from "./sdk/common/withPrefix"; -/** - * The base class definition for responseDto - **/ -export class ResponseDto { - /** - * Version of the API used for this response. - * @type {string} - **/ - #apiVersion?: string | null = undefined; - /** - * Version of the API used for this response. - * @returns {string} - **/ - get apiVersion() { - return this.#apiVersion; - } - /** - * Version of the API used for this response. - * @type {string} - **/ - set apiVersion(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#apiVersion = correctType ? value : String(value); - } - setApiVersion(value: string | null | undefined) { - this.apiVersion = value; - return this; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - #context?: string | null = undefined; - /** - * Context string provided by the client or system for request tracking. - * @returns {string} - **/ - get context() { - return this.#context; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - set context(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#context = correctType ? value : String(value); - } - setContext(value: string | null | undefined) { - this.context = value; - return this; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier assigned to the request/response. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - #method?: string | null = undefined; - /** - * Name of the API method invoked. - * @returns {string} - **/ - get method() { - return this.#method; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - set method(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#method = correctType ? value : String(value); - } - setMethod(value: string | null | undefined) { - this.method = value; - return this; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - #params: any = null; - /** - * Parameters sent with the request. - * @returns {any} - **/ - get params() { - return this.#params; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - set params(value: any) { - this.#params = value; - } - setParams(value: any) { - this.params = value; - return this; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - #data!: InstanceType>; - /** - * Main data payload of the response. - * @returns {ResponseDto.Data} - **/ - get data() { - return this.#data; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - set data(value: InstanceType>) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Data) { - this.#data = value; - } else { - this.#data = new ResponseDto.Data(value); - } - } - setData(value: InstanceType>) { - this.data = value; - return this; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - #error!: InstanceType; - /** - * Error details, if the request failed. - * @returns {ResponseDto.Error} - **/ - get error() { - return this.#error; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - set error(value: InstanceType) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Error) { - this.#error = value; - } else { - this.#error = new ResponseDto.Error(value); - } - } - setError(value: InstanceType) { - this.error = value; - return this; - } - /** - * The base class definition for data - **/ - static Data = class Data { - /** - * Single item returned by the API. - * @type {any} - **/ - #item: T | null = null; - /** - * Single item returned by the API. - * @returns {T} - **/ - get item(): T | null { - return this.#item; - } - /** - * Single item returned by the API. - * @type {any} - **/ - set item(value: any) { - this.#item = value; - } - setItem(value: any) { - this.item = value; - return this; - } - /** - * List of items returned by the API. - * @type {any} - **/ - #items: T[] = []; - /** - * List of items returned by the API. - * @returns {T[]} - **/ - get items(): T[] { - return this.#items; - } - /** - * List of items returned by the API. - * @type {T[]} - **/ - set items(value: T[]) { - this.#items = value; - } - setItems(value: T[]) { - this.items = value; - return this; - } - /** - * Link to edit this resource. - * @type {string} - **/ - #editLink?: string | null = undefined; - /** - * Link to edit this resource. - * @returns {string} - **/ - get editLink() { - return this.#editLink; - } - /** - * Link to edit this resource. - * @type {string} - **/ - set editLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#editLink = correctType ? value : String(value); - } - setEditLink(value: string | null | undefined) { - this.editLink = value; - return this; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - #selfLink?: string | null = undefined; - /** - * Link to retrieve this resource. - * @returns {string} - **/ - get selfLink() { - return this.#selfLink; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - set selfLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#selfLink = correctType ? value : String(value); - } - setSelfLink(value: string | null | undefined) { - this.selfLink = value; - return this; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - #kind?: string | null = undefined; - /** - * Resource type (kind) identifier. - * @returns {string} - **/ - get kind() { - return this.#kind; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - set kind(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#kind = correctType ? value : String(value); - } - setKind(value: string | null | undefined) { - this.kind = value; - return this; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - #fields?: string | null = undefined; - /** - * Selector specifying which fields are included in a partial response. - * @returns {string} - **/ - get fields() { - return this.#fields; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - set fields(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#fields = correctType ? value : String(value); - } - setFields(value: string | null | undefined) { - this.fields = value; - return this; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - #etag?: string | null = undefined; - /** - * ETag of the resource, used for caching/version control. - * @returns {string} - **/ - get etag() { - return this.#etag; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - set etag(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#etag = correctType ? value : String(value); - } - setEtag(value: string | null | undefined) { - this.etag = value; - return this; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - #cursor?: string | null = undefined; - /** - * Cursor for paginated data fetching. - * @returns {string} - **/ - get cursor() { - return this.#cursor; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - set cursor(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#cursor = correctType ? value : String(value); - } - setCursor(value: string | null | undefined) { - this.cursor = value; - return this; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier of the resource. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Language code of the response data. - * @type {string} - **/ - #lang?: string | null = undefined; - /** - * Language code of the response data. - * @returns {string} - **/ - get lang() { - return this.#lang; - } - /** - * Language code of the response data. - * @type {string} - **/ - set lang(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#lang = correctType ? value : String(value); - } - setLang(value: string | null | undefined) { - this.lang = value; - return this; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - #updated?: string | null = undefined; - /** - * Last modification time of the resource. - * @returns {string} - **/ - get updated() { - return this.#updated; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - set updated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#updated = correctType ? value : String(value); - } - setUpdated(value: string | null | undefined) { - this.updated = value; - return this; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - #currentItemCount?: number | null = undefined; - /** - * Number of items in the current response page. - * @returns {number} - **/ - get currentItemCount() { - return this.#currentItemCount; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - set currentItemCount(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#currentItemCount = parsedValue; - } - } - setCurrentItemCount(value: number | null | undefined) { - this.currentItemCount = value; - return this; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - #itemsPerPage?: number | null = undefined; - /** - * Maximum number of items per page. - * @returns {number} - **/ - get itemsPerPage() { - return this.#itemsPerPage; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - set itemsPerPage(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#itemsPerPage = parsedValue; - } - } - setItemsPerPage(value: number | null | undefined) { - this.itemsPerPage = value; - return this; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - #startIndex?: number | null = undefined; - /** - * Index of the first item in the current page. - * @returns {number} - **/ - get startIndex() { - return this.#startIndex; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - set startIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#startIndex = parsedValue; - } - } - setStartIndex(value: number | null | undefined) { - this.startIndex = value; - return this; - } - /** - * Total number of items available. - * @type {number} - **/ - #totalItems?: number | null = undefined; - /** - * Total number of items available. - * @returns {number} - **/ - get totalItems() { - return this.#totalItems; - } - /** - * Total number of items available. - * @type {number} - **/ - set totalItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalItems = parsedValue; - } - } - setTotalItems(value: number | null | undefined) { - this.totalItems = value; - return this; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - #totalAvailableItems?: number | null = undefined; - /** - * Number of items available for this user/query. - * @returns {number} - **/ - get totalAvailableItems() { - return this.#totalAvailableItems; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - set totalAvailableItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalAvailableItems = parsedValue; - } - } - setTotalAvailableItems(value: number | null | undefined) { - this.totalAvailableItems = value; - return this; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - #pageIndex?: number | null = undefined; - /** - * Current page index in the pagination. - * @returns {number} - **/ - get pageIndex() { - return this.#pageIndex; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - set pageIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#pageIndex = parsedValue; - } - } - setPageIndex(value: number | null | undefined) { - this.pageIndex = value; - return this; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - #totalPages?: number | null = undefined; - /** - * Total number of pages in the pagination. - * @returns {number} - **/ - get totalPages() { - return this.#totalPages; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - set totalPages(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalPages = parsedValue; - } - } - setTotalPages(value: number | null | undefined) { - this.totalPages = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.item !== undefined) { - this.item = d.item; - } - if (d.items !== undefined) { - this.items = d.items; - } - if (d.editLink !== undefined) { - this.editLink = d.editLink; - } - if (d.selfLink !== undefined) { - this.selfLink = d.selfLink; - } - if (d.kind !== undefined) { - this.kind = d.kind; - } - if (d.fields !== undefined) { - this.fields = d.fields; - } - if (d.etag !== undefined) { - this.etag = d.etag; - } - if (d.cursor !== undefined) { - this.cursor = d.cursor; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.lang !== undefined) { - this.lang = d.lang; - } - if (d.updated !== undefined) { - this.updated = d.updated; - } - if (d.currentItemCount !== undefined) { - this.currentItemCount = d.currentItemCount; - } - if (d.itemsPerPage !== undefined) { - this.itemsPerPage = d.itemsPerPage; - } - if (d.startIndex !== undefined) { - this.startIndex = d.startIndex; - } - if (d.totalItems !== undefined) { - this.totalItems = d.totalItems; - } - if (d.totalAvailableItems !== undefined) { - this.totalAvailableItems = d.totalAvailableItems; - } - if (d.pageIndex !== undefined) { - this.pageIndex = d.pageIndex; - } - if (d.totalPages !== undefined) { - this.totalPages = d.totalPages; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - item: this.#item, - items: this.#items, - editLink: this.#editLink, - selfLink: this.#selfLink, - kind: this.#kind, - fields: this.#fields, - etag: this.#etag, - cursor: this.#cursor, - id: this.#id, - lang: this.#lang, - updated: this.#updated, - currentItemCount: this.#currentItemCount, - itemsPerPage: this.#itemsPerPage, - startIndex: this.#startIndex, - totalItems: this.#totalItems, - totalAvailableItems: this.#totalAvailableItems, - pageIndex: this.#pageIndex, - totalPages: this.#totalPages, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - item: "item", - items: "items", - editLink: "editLink", - selfLink: "selfLink", - kind: "kind", - fields: "fields", - etag: "etag", - cursor: "cursor", - id: "id", - lang: "lang", - updated: "updated", - currentItemCount: "currentItemCount", - itemsPerPage: "itemsPerPage", - startIndex: "startIndex", - totalItems: "totalItems", - totalAvailableItems: "totalAvailableItems", - pageIndex: "pageIndex", - totalPages: "totalPages", - }; - } - /** - * Creates an instance of ResponseDto.Data, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.DataType) { - return new ResponseDto.Data(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Data, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep>, - ) { - return new ResponseDto.Data(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto.Data({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Data(this.toJSON()); - } - }; - /** - * The base class definition for error - **/ - static Error = class Error { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - #code: number = 0; - /** - * Numeric error code representing the failure. - * @returns {number} - **/ - get code() { - return this.#code; - } - /** - * Numeric error code representing the failure. - * @type {number} - **/ - set code(value: number) { - const correctType = typeof value === "number"; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#code = parsedValue; - } - } - setCode(value: number) { - this.code = value; - return this; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - #message: string = ""; - /** - * Human-readable explanation of the error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - set message(value: string) { - this.#message = String(value); - } - setMessage(value: string) { - this.message = value; - return this; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - #messageTranslated: string = ""; - /** - * Localized/translated version of the error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - set messageTranslated(value: string) { - this.#messageTranslated = String(value); - } - setMessageTranslated(value: string) { - this.messageTranslated = value; - return this; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - #errors: InstanceType[] = []; - /** - * Detailed list of error objects. - * @returns {ResponseDto.Error.Errors} - **/ - get errors() { - return this.#errors; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - set errors(value: InstanceType[]) { - // For arrays, you only can pass arrays to the object - if (!Array.isArray(value)) { - return; - } - if (value.length > 0 && value[0] instanceof ResponseDto.Error.Errors) { - this.#errors = value; - } else { - this.#errors = value.map((item) => new ResponseDto.Error.Errors(item)); - } - } - setErrors(value: InstanceType[]) { - this.errors = value; - return this; - } - /** - * The base class definition for errors - **/ - static Errors = class Errors { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - #domain?: string | null = undefined; - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @returns {string} - **/ - get domain() { - return this.#domain; - } - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - set domain(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#domain = correctType ? value : String(value); - } - setDomain(value: string | null | undefined) { - this.domain = value; - return this; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - #reason?: string | null = undefined; - /** - * Reason identifier for the error. - * @returns {string} - **/ - get reason() { - return this.#reason; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - set reason(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#reason = correctType ? value : String(value); - } - setReason(value: string | null | undefined) { - this.reason = value; - return this; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - #message?: string | null = undefined; - /** - * Human-readable explanation of the sub-error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - set message(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#message = correctType ? value : String(value); - } - setMessage(value: string | null | undefined) { - this.message = value; - return this; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - #messageTranslated?: string | null = undefined; - /** - * Localized/translated version of the sub-error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - set messageTranslated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#messageTranslated = correctType ? value : String(value); - } - setMessageTranslated(value: string | null | undefined) { - this.messageTranslated = value; - return this; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - #location?: string | null = undefined; - /** - * Field or parameter in which the error occurred. - * @returns {string} - **/ - get location() { - return this.#location; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - set location(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#location = correctType ? value : String(value); - } - setLocation(value: string | null | undefined) { - this.location = value; - return this; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - #locationType?: string | null = undefined; - /** - * Type of location (e.g., parameter, header). - * @returns {string} - **/ - get locationType() { - return this.#locationType; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - set locationType(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#locationType = correctType ? value : String(value); - } - setLocationType(value: string | null | undefined) { - this.locationType = value; - return this; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - #extendedHelp?: string | null = undefined; - /** - * URL linking to additional documentation about the error. - * @returns {string} - **/ - get extendedHelp() { - return this.#extendedHelp; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - set extendedHelp(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#extendedHelp = correctType ? value : String(value); - } - setExtendedHelp(value: string | null | undefined) { - this.extendedHelp = value; - return this; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - #sendReport?: string | null = undefined; - /** - * URL to submit a report for this error. - * @returns {string} - **/ - get sendReport() { - return this.#sendReport; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - set sendReport(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#sendReport = correctType ? value : String(value); - } - setSendReport(value: string | null | undefined) { - this.sendReport = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.domain !== undefined) { - this.domain = d.domain; - } - if (d.reason !== undefined) { - this.reason = d.reason; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.location !== undefined) { - this.location = d.location; - } - if (d.locationType !== undefined) { - this.locationType = d.locationType; - } - if (d.extendedHelp !== undefined) { - this.extendedHelp = d.extendedHelp; - } - if (d.sendReport !== undefined) { - this.sendReport = d.sendReport; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - domain: this.#domain, - reason: this.#reason, - message: this.#message, - messageTranslated: this.#messageTranslated, - location: this.#location, - locationType: this.#locationType, - extendedHelp: this.#extendedHelp, - sendReport: this.#sendReport, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - domain: "domain", - reason: "reason", - message: "message", - messageTranslated: "messageTranslated", - location: "location", - locationType: "locationType", - extendedHelp: "extendedHelp", - sendReport: "sendReport", - }; - } - /** - * Creates an instance of ResponseDto.Error.Errors, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType.ErrorsType) { - return new ResponseDto.Error.Errors(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error.Errors, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep, - ) { - return new ResponseDto.Error.Errors(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error.Errors({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error.Errors(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.code !== undefined) { - this.code = d.code; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.errors !== undefined) { - this.errors = d.errors; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - code: this.#code, - message: this.#message, - messageTranslated: this.#messageTranslated, - errors: this.#errors, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - code: "code", - message: "message", - messageTranslated: "messageTranslated", - errors$: "errors", - get errors() { - return withPrefix( - "error.errors[:i]", - ResponseDto.Error.Errors.Fields, - ); - }, - }; - } - /** - * Creates an instance of ResponseDto.Error, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType) { - return new ResponseDto.Error(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep) { - return new ResponseDto.Error(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - this.#lateInitFields(); - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.apiVersion !== undefined) { - this.apiVersion = d.apiVersion; - } - if (d.context !== undefined) { - this.context = d.context; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.method !== undefined) { - this.method = d.method; - } - if (d.params !== undefined) { - this.params = d.params; - } - if (d.data !== undefined) { - this.data = d.data; - } - if (d.error !== undefined) { - this.error = d.error; - } - this.#lateInitFields(data); - } - /** - * These are the class instances, which need to be initialised, regardless of the constructor incoming data - **/ - #lateInitFields(data = {}) { - const d = data as Partial>; - if (!(d.data instanceof ResponseDto.Data)) { - this.data = new ResponseDto.Data(d.data || {}); - } - if (!(d.error instanceof ResponseDto.Error)) { - this.error = new ResponseDto.Error(d.error || {}); - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - apiVersion: this.#apiVersion, - context: this.#context, - id: this.#id, - method: this.#method, - params: this.#params, - data: this.#data, - error: this.#error, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - apiVersion: "apiVersion", - context: "context", - id: "id", - method: "method", - params: "params", - data$: "data", - get data() { - return withPrefix("data", ResponseDto.Data.Fields); - }, - error$: "error", - get error() { - return withPrefix("error", ResponseDto.Error.Fields); - }, - }; - } - /** - * Creates an instance of ResponseDto, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType) { - return new ResponseDto(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep>) { - return new ResponseDto(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto(this.toJSON()); - } -} -export abstract class ResponseDtoFactory { - abstract create(data: unknown): ResponseDto; -} -type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; -/** - * The base type definition for responseDto - **/ -export type ResponseDtoType = { - /** - * Version of the API used for this response. - * @type {string} - **/ - apiVersion?: string; - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - context?: string; - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - id?: string; - /** - * Name of the API method invoked. - * @type {string} - **/ - method?: string; - /** - * Parameters sent with the request. - * @type {any} - **/ - params: any; - /** - * Main data payload of the response. - * @type {ResponseDtoType.DataType} - **/ - data: ResponseDtoType.DataType; - /** - * Error details, if the request failed. - * @type {ResponseDtoType.ErrorType} - **/ - error: ResponseDtoType.ErrorType; -}; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ResponseDtoType { - /** - * The base type definition for dataType - **/ - export type DataType = { - /** - * Single item returned by the API. - * @type {any} - **/ - item2: T; - /** - * List of items returned by the API. - * @type {any} - **/ - items: any; - /** - * Link to edit this resource. - * @type {string} - **/ - editLink?: string; - /** - * Link to retrieve this resource. - * @type {string} - **/ - selfLink?: string; - /** - * Resource type (kind) identifier. - * @type {string} - **/ - kind?: string; - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - fields?: string; - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - etag?: string; - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - cursor?: string; - /** - * Unique identifier of the resource. - * @type {string} - **/ - id?: string; - /** - * Language code of the response data. - * @type {string} - **/ - lang?: string; - /** - * Last modification time of the resource. - * @type {string} - **/ - updated?: string; - /** - * Number of items in the current response page. - * @type {number} - **/ - currentItemCount?: number; - /** - * Maximum number of items per page. - * @type {number} - **/ - itemsPerPage?: number; - /** - * Index of the first item in the current page. - * @type {number} - **/ - startIndex?: number; - /** - * Total number of items available. - * @type {number} - **/ - totalItems?: number; - /** - * Number of items available for this user/query. - * @type {number} - **/ - totalAvailableItems?: number; - /** - * Current page index in the pagination. - * @type {number} - **/ - pageIndex?: number; - /** - * Total number of pages in the pagination. - * @type {number} - **/ - totalPages?: number; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace DataType {} - /** - * The base type definition for errorType - **/ - export type ErrorType = { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - code: number; - /** - * Human-readable explanation of the error. - * @type {string} - **/ - message: string; - /** - * Localized/translated version of the error message. - * @type {string} - **/ - messageTranslated: string; - /** - * Detailed list of error objects. - * @type {ResponseDtoType.ErrorType.ErrorsType[]} - **/ - errors: ResponseDtoType.ErrorType.ErrorsType[]; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorType { - /** - * The base type definition for errorsType - **/ - export type ErrorsType = { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - domain?: string; - /** - * Reason identifier for the error. - * @type {string} - **/ - reason?: string; - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - message?: string; - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - messageTranslated?: string; - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - location?: string; - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - locationType?: string; - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - extendedHelp?: string; - /** - * URL to submit a report for this error. - * @type {string} - **/ - sendReport?: string; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorsType {} - } -} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json deleted file mode 100644 index 7a3dc447..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "sdk", - "version": "1.0.0", - "description": "Auto-generated package.json", - "main": "index.js", - "scripts": { - "build": "echo 'build script here'", - "test": "echo 'test script here'" - }, - "dependencies": { - "@types/qs": "^6.14.0", - "qs": "^6.14.0" - } -} \ No newline at end of file diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml deleted file mode 100644 index 0dcb101c..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: googleEnvelop -description: - Generating envelop API responses using Emi itself. - Emi codegen is so strong that can generate deep classes in javascript which could be used - in itself and in this example we are doing it. - - All responses can be wrapped in google json styleguide, which gives extream consistency. - -dtos: - - name: response - fields: - - name: apiVersion - type: string? - description: Version of the API used for this response. - - name: context - type: string? - description: Context string provided by the client or system for request tracking. - - name: id - type: string? - description: Unique identifier assigned to the request/response. - - name: method - type: string? - description: Name of the API method invoked. - - name: params - type: any - description: Parameters sent with the request. - - name: data - type: object - description: Main data payload of the response. - fields: - - name: item - type: any - description: Single item returned by the API. - - name: items - type: any - description: List of items returned by the API. - - name: editLink - type: string? - description: Link to edit this resource. - - name: selfLink - type: string? - description: Link to retrieve this resource. - - name: kind - type: string? - description: Resource type (kind) identifier. - - name: fields - type: string? - description: Selector specifying which fields are included in a partial response. - - name: etag - type: string? - description: ETag of the resource, used for caching/version control. - - name: cursor - type: string? - description: Cursor for paginated data fetching. - - name: id - type: string? - description: Unique identifier of the resource. - - name: lang - type: string? - description: Language code of the response data. - - name: updated - type: string? - description: Last modification time of the resource. - - name: currentItemCount - type: int? - description: Number of items in the current response page. - - name: itemsPerPage - type: int? - description: Maximum number of items per page. - - name: startIndex - type: int? - description: Index of the first item in the current page. - - name: totalItems - type: int? - description: Total number of items available. - - name: totalAvailableItems - type: int? - description: Number of items available for this user/query. - - name: pageIndex - type: int? - description: Current page index in the pagination. - - name: totalPages - type: int? - description: Total number of pages in the pagination. - - name: error - type: object - description: Error details, if the request failed. - fields: - - name: code - type: int - description: Numeric error code representing the failure. - - name: message - type: string - description: Human-readable explanation of the error. - - name: messageTranslated - type: string - description: Localized/translated version of the error message. - - name: errors - type: array - description: Detailed list of error objects. - fields: - - name: domain - type: string? - description: Logical grouping of the error (e.g., global, usageLimits). - - name: reason - type: string? - description: Reason identifier for the error. - - name: message - type: string? - description: Human-readable explanation of the sub-error. - - name: messageTranslated - type: string? - description: Localized/translated version of the sub-error message. - - name: location - type: string? - description: Field or parameter in which the error occurred. - - name: locationType - type: string? - description: Type of location (e.g., parameter, header). - - name: extendedHelp - type: string? - description: URL linking to additional documentation about the error. - - name: sendReport - type: string? - description: URL to submit a report for this error. diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts deleted file mode 100644 index 2fc2601b..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; -import { ResponseDto } from "./generated/ResponseDto"; -// Use this class to generate a GResponse. -export class GResponse extends ResponseDto implements EnvelopeClass { - creator?: CreatorSignature | null; - constructor(data?: unknown) { - super(data); - } - setCreator(fn: CreatorSignature) { - this.creator = fn; - return this; - } - /** - * GResponse can have data.item or data.items - * We create that based on incoming data tpye, so there is no need for 2 different - * classes, one for array and other for singular - * @param data - * @returns - */ - inject(body: any): this { - this.applyFromObject(body); - if ((body as any)?.data) { - if (!this.data) { - this.setData({} as any); - } - if ( - Array.isArray(body?.data.items) && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItems( - body?.data?.items?.map((item: unknown) => this.creator?.(item)), - ); - } else if ( - typeof body?.data?.item === "object" && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItem(this.creator(body?.data?.item)); - } else { - this.data?.setItem(body?.data?.item); - } - } - return this; - } -} diff --git a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/index.ts b/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/index.ts deleted file mode 100644 index 63d3ef26..00000000 --- a/examples/allegro-sdk/javascript/gen/offer/user-offer-information/sdk/envelopes/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./google-json-style-guide/index"; -export * from "./flat-array/FlatArray"; diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.kt index d0399c79..44f5f6ea 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import kotlinx.serialization.* -import okhttp3.* -import okhttp3.RequestBody.Companion.toRequestBody import emikot.ClientContext -import kotlinx.serialization.json.* -import emikot.MaybeField import emikot.Maybe -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.HttpUrl.Companion.toHttpUrl +import emikot.MaybeField import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import kotlinx.serialization.* +import kotlinx.serialization.json.* +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action BatchOfferPromotionPackageModificationAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPublishUnpublishAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPublishUnpublishAction.kt index 448628e3..c4d4f25a 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPublishUnpublishAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/BatchOfferPublishUnpublishAction.kt @@ -1,15 +1,15 @@ package unknownpackage +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.* -import emikot.MaybeField +import kotlinx.serialization.json.* import okhttp3.* -import okhttp3.MediaType.Companion.toMediaType import okhttp3.HttpUrl.Companion.toHttpUrl -import emikot.ClientContext -import kotlinx.serialization.json.* -import emikot.Maybe +import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import kotlinx.coroutines.Dispatchers /** * Action to communicate with the action BatchOfferPublishUnpublishAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.kt index be24df74..2182eba9 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.kt @@ -1,15 +1,15 @@ package unknownpackage +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.MaybeField -import emikot.Maybe -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl -import emikot.ClientContext import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/CreateOfferBasedOnProductAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/CreateOfferBasedOnProductAction.kt index 944999b6..1bf066f7 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/CreateOfferBasedOnProductAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/CreateOfferBasedOnProductAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.MediaType.Companion.toMediaType +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.MaybeField import okhttp3.* -import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.HttpUrl.Companion.toHttpUrl -import kotlinx.coroutines.withContext -import emikot.ClientContext -import emikot.Maybe +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action CreateOfferBasedOnProductAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/DeleteADraftOfferAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/DeleteADraftOfferAction.kt index cf40a476..05c91c68 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/DeleteADraftOfferAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/DeleteADraftOfferAction.kt @@ -1,13 +1,13 @@ package unknownpackage +import emikot.ClientContext +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.* import kotlinx.serialization.json.* import okhttp3.* -import okhttp3.RequestBody.Companion.toRequestBody -import kotlinx.coroutines.withContext -import okhttp3.MediaType.Companion.toMediaType import okhttp3.HttpUrl.Companion.toHttpUrl -import kotlinx.coroutines.Dispatchers -import emikot.ClientContext -import kotlinx.serialization.* +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action DeleteADraftOfferAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/EditAnOfferAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/EditAnOfferAction.kt index 082f258b..b9b72ce7 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/EditAnOfferAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/EditAnOfferAction.kt @@ -1,15 +1,15 @@ package unknownpackage +import emikot.ClientContext import emikot.Maybe -import okhttp3.HttpUrl.Companion.toHttpUrl +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.MaybeField import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import kotlinx.coroutines.Dispatchers -import emikot.ClientContext -import kotlinx.serialization.* /** * Action to communicate with the action EditAnOfferAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.kt index ec46f3a4..e74e944e 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.* -import okhttp3.RequestBody.Companion.toRequestBody +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import emikot.ClientContext import kotlinx.serialization.* -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.HttpUrl.Companion.toHttpUrl import kotlinx.serialization.json.* -import emikot.MaybeField -import emikot.Maybe +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action GetAllAvailableOfferPromotionPackagesAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOfferPromotionPackagesAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOfferPromotionPackagesAction.kt index 450a118e..fb5043ca 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOfferPromotionPackagesAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOfferPromotionPackagesAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import kotlinx.coroutines.Dispatchers import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.* import kotlinx.serialization.json.* import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import kotlinx.coroutines.withContext -import kotlinx.serialization.* -import emikot.MaybeField -import emikot.Maybe -import okhttp3.HttpUrl.Companion.toHttpUrl /** * Action to communicate with the action GetOfferPromotionPackagesAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOffersWithMissingParametersAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOffersWithMissingParametersAction.kt index 6380f82a..6d76b9a8 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOffersWithMissingParametersAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetOffersWithMissingParametersAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import emikot.MaybeField +import emikot.ClientContext import emikot.Maybe -import okhttp3.* -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl +import emikot.MaybeField import kotlinx.coroutines.Dispatchers -import emikot.ClientContext +import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import kotlinx.coroutines.withContext +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action GetOffersWithMissingParametersAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.kt index c0fb2979..103787ed 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.kt @@ -1,15 +1,15 @@ package unknownpackage import emikot.ClientContext -import kotlinx.serialization.* -import kotlinx.serialization.json.* +import emikot.Maybe import emikot.MaybeField -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.HttpUrl.Companion.toHttpUrl import kotlinx.coroutines.Dispatchers -import emikot.Maybe +import kotlinx.coroutines.withContext +import kotlinx.serialization.* +import kotlinx.serialization.json.* import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import kotlinx.coroutines.withContext /** * Action to communicate with the action GetPromoOptionsForSellerSOffersAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandDetailedResultAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandDetailedResultAction.kt index a20bec4e..35616df7 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandDetailedResultAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandDetailedResultAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl -import kotlinx.coroutines.withContext +import emikot.ClientContext import emikot.Maybe -import okhttp3.* -import okhttp3.MediaType.Companion.toMediaType +import emikot.MaybeField import kotlinx.coroutines.Dispatchers -import emikot.ClientContext +import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.MaybeField +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action ModificationCommandDetailedResultAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandSummaryAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandSummaryAction.kt index bdea1afd..79b07286 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandSummaryAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModificationCommandSummaryAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.* -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.RequestBody.Companion.toRequestBody +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import emikot.MaybeField -import emikot.Maybe -import okhttp3.HttpUrl.Companion.toHttpUrl -import emikot.ClientContext import kotlinx.serialization.* import kotlinx.serialization.json.* +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action ModificationCommandSummaryAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.kt index ba2ea1c7..0281791a 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import kotlinx.serialization.* -import kotlinx.serialization.json.* +import emikot.ClientContext +import emikot.Maybe import emikot.MaybeField -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import emikot.ClientContext -import emikot.Maybe +import kotlinx.serialization.* +import kotlinx.serialization.json.* import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action ModifyOfferPromotionPackagesAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.kt index b1300d9a..5325641a 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.kt @@ -1,15 +1,15 @@ package unknownpackage +import emikot.ClientContext +import emikot.Maybe import emikot.MaybeField -import okhttp3.MediaType.Companion.toMediaType import kotlinx.coroutines.Dispatchers -import emikot.ClientContext +import kotlinx.coroutines.withContext +import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.Maybe import okhttp3.* -import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.HttpUrl.Companion.toHttpUrl -import kotlinx.coroutines.withContext -import kotlinx.serialization.* +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action ModifyTheBuyNowPriceInAnOfferAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandDetailedReportAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandDetailedReportAction.kt index 0a431340..8f8e483e 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandDetailedReportAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandDetailedReportAction.kt @@ -1,15 +1,15 @@ package unknownpackage +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.Maybe import okhttp3.* -import kotlinx.coroutines.withContext -import emikot.ClientContext -import emikot.MaybeField +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl /** * Action to communicate with the action PublishCommandDetailedReportAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandSummaryAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandSummaryAction.kt index 56930ea6..6baf66c1 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandSummaryAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-management/PublishCommandSummaryAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import kotlinx.serialization.* import kotlinx.serialization.json.* import okhttp3.* -import kotlinx.coroutines.Dispatchers -import emikot.ClientContext -import kotlinx.serialization.* -import emikot.MaybeField -import emikot.Maybe +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action PublishCommandSummaryAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-translations/DeleteOfferTranslationAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-translations/DeleteOfferTranslationAction.kt index 76fcc453..0521d8e1 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-translations/DeleteOfferTranslationAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-translations/DeleteOfferTranslationAction.kt @@ -1,13 +1,13 @@ package unknownpackage import emikot.ClientContext +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext /** * Action to communicate with the action DeleteOfferTranslationAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-translations/GetOfferTranslationsAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-translations/GetOfferTranslationsAction.kt index 51a63e55..ea9425ad 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-translations/GetOfferTranslationsAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-translations/GetOfferTranslationsAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.RequestBody.Companion.toRequestBody +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.Maybe import okhttp3.* import okhttp3.HttpUrl.Companion.toHttpUrl -import kotlinx.coroutines.Dispatchers -import emikot.ClientContext -import emikot.MaybeField +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action GetOfferTranslationsAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/offer-translations/UpdateOfferTranslationAction.kt b/examples/allegro-sdk/kotlin/gen/offer/offer-translations/UpdateOfferTranslationAction.kt index 4abfe782..48566e04 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/offer-translations/UpdateOfferTranslationAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/offer-translations/UpdateOfferTranslationAction.kt @@ -1,15 +1,15 @@ package unknownpackage +import emikot.ClientContext import emikot.Maybe -import okhttp3.* -import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import emikot.ClientContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.MaybeField +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType -import kotlinx.coroutines.Dispatchers +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action UpdateOfferTranslationAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.kt b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.kt index 1232349b..c6cb5390 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.* -import okhttp3.HttpUrl.Companion.toHttpUrl +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import emikot.ClientContext import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.MaybeField +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import emikot.Maybe /** * Action to communicate with the action GetAllDataOfTheParticularProductOfferAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.kt b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.kt index ab6a2dd7..754cbbdd 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.* -import okhttp3.MediaType.Companion.toMediaType +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import kotlinx.serialization.* import kotlinx.serialization.json.* -import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.* import okhttp3.HttpUrl.Companion.toHttpUrl -import kotlinx.coroutines.Dispatchers -import emikot.ClientContext -import kotlinx.serialization.* -import emikot.MaybeField -import emikot.Maybe +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action GetEventsAboutTheSellerSOffersAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.kt b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.kt index 78f46b2a..17dae27b 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.kt @@ -1,15 +1,15 @@ package unknownpackage import emikot.ClientContext -import kotlinx.serialization.* -import okhttp3.* +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import kotlinx.serialization.* import kotlinx.serialization.json.* -import emikot.MaybeField -import emikot.Maybe +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl -import kotlinx.coroutines.Dispatchers /** * Action to communicate with the action GetSelectedDataOfTheParticularProductOfferAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSellersOffersAction.kt b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSellersOffersAction.kt index aa6305c4..1d555800 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSellersOffersAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSellersOffersAction.kt @@ -1,15 +1,15 @@ package unknownpackage +import emikot.ClientContext +import emikot.Maybe +import emikot.MaybeField +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.* import kotlinx.serialization.json.* +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody -import okhttp3.HttpUrl.Companion.toHttpUrl -import emikot.ClientContext -import emikot.MaybeField -import emikot.Maybe -import okhttp3.* -import kotlinx.coroutines.Dispatchers /** * Action to communicate with the action GetSellersOffersAction */ diff --git a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.kt b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.kt index 202b9f03..b456f37a 100644 --- a/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.kt +++ b/examples/allegro-sdk/kotlin/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.kt @@ -1,15 +1,15 @@ package unknownpackage -import okhttp3.RequestBody.Companion.toRequestBody -import kotlinx.coroutines.withContext import emikot.ClientContext -import kotlinx.serialization.* -import kotlinx.serialization.json.* +import emikot.Maybe import emikot.MaybeField -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.HttpUrl.Companion.toHttpUrl import kotlinx.coroutines.Dispatchers -import emikot.Maybe +import kotlinx.coroutines.withContext +import kotlinx.serialization.* +import kotlinx.serialization.json.* import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody /** * Action to communicate with the action GetSmartClassificationReportOfTheParticularOfferAction */ diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.ts index bda5c684..acc76a3e 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPromotionPackageModificationAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -230,9 +223,11 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria} **/ - #offerCriteria: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria - >[] = []; + #offerCriteria: MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria + > + > = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.OfferCriteria} @@ -245,32 +240,63 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria} **/ set offerCriteria( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.OfferCriteria + ) { + this.#offerCriteria = MArray.of(value); + } else { + this.#offerCriteria = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.OfferCriteria( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.OfferCriteria - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offerCriteria = value; - } else { - this.#offerCriteria = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.OfferCriteria( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offerCriteria = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to offerCriteria, because it needs MArray instance or an Array.", + ); } setOfferCriteria( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria + >[], ) { this.offerCriteria = value; return this; @@ -321,9 +347,11 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces} **/ - #additionalMarketplaces: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces - >[] = []; + #additionalMarketplaces: MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces + > + > = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces} @@ -336,32 +364,63 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces} **/ set additionalMarketplaces( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces + >[], ) { this.additionalMarketplaces = value; return this; @@ -374,9 +433,11 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers} **/ - #offers: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers - >[] = []; + #offers: MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers + > + > = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers} @@ -389,32 +450,63 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers} **/ set offers( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue as any; + return; } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } setOffers( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.OfferCriteria.Offers + >[], ) { this.offers = value; return this; @@ -730,9 +822,11 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages + > + > = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages} @@ -745,33 +839,64 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq.Modification + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq.Modification - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.Modification.ExtraPackages + >[], ) { this.extraPackages = value; return this; @@ -1317,9 +1442,11 @@ export class BatchOfferPromotionPackageModificationActionReq { * * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages + > + > = MArray.of([]); /** * * @returns {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages} @@ -1332,33 +1459,64 @@ export class BatchOfferPromotionPackageModificationActionReq { * @type {BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPromotionPackageModificationActionReq + .AdditionalMarketplaces.Modification.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPromotionPackageModificationActionReq - .AdditionalMarketplaces.Modification.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages + > + > + | InstanceType< + typeof BatchOfferPromotionPackageModificationActionReq.AdditionalMarketplaces.Modification.ExtraPackages + >[], ) { this.extraPackages = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.ts index 14c8ad04..fb29eac4 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/BatchOfferPublishUnpublishAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -174,9 +167,9 @@ export class BatchOfferPublishUnpublishActionReq { * * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria} **/ - #offerCriteria: InstanceType< - typeof BatchOfferPublishUnpublishActionReq.OfferCriteria - >[] = []; + #offerCriteria: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {BatchOfferPublishUnpublishActionReq.OfferCriteria} @@ -189,28 +182,56 @@ export class BatchOfferPublishUnpublishActionReq { * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria} **/ set offerCriteria( - value: InstanceType< - typeof BatchOfferPublishUnpublishActionReq.OfferCriteria - >[], + value: + | MArray< + InstanceType + > + | InstanceType< + typeof BatchOfferPublishUnpublishActionReq.OfferCriteria + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof BatchOfferPublishUnpublishActionReq.OfferCriteria + ) { + this.#offerCriteria = MArray.of(value); + } else { + this.#offerCriteria = MArray.of( + value.map( + (item) => + new BatchOfferPublishUnpublishActionReq.OfferCriteria(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof BatchOfferPublishUnpublishActionReq.OfferCriteria - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offerCriteria = value; - } else { - this.#offerCriteria = value.map( - (item) => new BatchOfferPublishUnpublishActionReq.OfferCriteria(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offerCriteria = mcastValue as any; + return; } + console.warn( + "Cannot assing value to offerCriteria, because it needs MArray instance or an Array.", + ); } setOfferCriteria( - value: InstanceType< - typeof BatchOfferPublishUnpublishActionReq.OfferCriteria - >[], + value: + | MArray< + InstanceType + > + | InstanceType< + typeof BatchOfferPublishUnpublishActionReq.OfferCriteria + >[], ) { this.offerCriteria = value; return this; @@ -259,9 +280,11 @@ export class BatchOfferPublishUnpublishActionReq { * * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers} **/ - #offers: InstanceType< - typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers - >[] = []; + #offers: MArray< + InstanceType< + typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers + > + > = MArray.of([]); /** * * @returns {BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers} @@ -274,30 +297,63 @@ export class BatchOfferPublishUnpublishActionReq { * @type {BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers} **/ set offers( - value: InstanceType< - typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers + > + > + | InstanceType< + typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map( + (item) => + new BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => - new BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } setOffers( - value: InstanceType< - typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers - >[], + value: + | MArray< + InstanceType< + typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers + > + > + | InstanceType< + typeof BatchOfferPublishUnpublishActionReq.OfferCriteria.Offers + >[], ) { this.offers = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.ts index eb5d13b3..1d118924 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/CheckTheProcessingStatusOfAPOSTOrPATCHRequestAction.ts @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/CreateOfferBasedOnProductAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/CreateOfferBasedOnProductAction.ts index 1ba43c43..a7af5331 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/CreateOfferBasedOnProductAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/CreateOfferBasedOnProductAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -754,9 +747,9 @@ export class CreateOfferBasedOnProductActionReq { * Product details and associated quantities * @type {CreateOfferBasedOnProductActionReq.ProductSet} **/ - #productSet: InstanceType< - typeof CreateOfferBasedOnProductActionReq.ProductSet - >[] = []; + #productSet: MArray< + InstanceType + > = MArray.of([]); /** * Product details and associated quantities * @returns {CreateOfferBasedOnProductActionReq.ProductSet} @@ -769,24 +762,51 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.ProductSet} **/ set productSet( - value: InstanceType[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof CreateOfferBasedOnProductActionReq.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map( + (item) => new CreateOfferBasedOnProductActionReq.ProductSet(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof CreateOfferBasedOnProductActionReq.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => new CreateOfferBasedOnProductActionReq.ProductSet(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue as any; + return; } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } setProductSet( - value: InstanceType[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { this.productSet = value; return this; @@ -1112,9 +1132,9 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.Attachments} **/ - #attachments: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Attachments - >[] = []; + #attachments: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.Attachments} @@ -1127,28 +1147,51 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.Attachments} **/ set attachments( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Attachments - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof CreateOfferBasedOnProductActionReq.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map( + (item) => new CreateOfferBasedOnProductActionReq.Attachments(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof CreateOfferBasedOnProductActionReq.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => new CreateOfferBasedOnProductActionReq.Attachments(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue as any; + return; } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Attachments - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { this.attachments = value; return this; @@ -1879,9 +1922,11 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.ProductSet.Deposits} **/ - #deposits: InstanceType< - typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits - >[] = []; + #deposits: MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits + > + > = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.ProductSet.Deposits} @@ -1894,30 +1939,63 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.ProductSet.Deposits} **/ set deposits( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.ProductSet.Deposits( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.ProductSet.Deposits(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Deposits + >[], ) { this.deposits = value; return this; @@ -2043,9 +2121,11 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters} **/ - #parameters: InstanceType< - typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters - >[] = []; + #parameters: MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters + > + > = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters} @@ -2058,32 +2138,63 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters} **/ set parameters( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.ProductSet.Product.Parameters + >[], ) { this.parameters = value; return this; @@ -5478,9 +5589,11 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.CompatibilityList.Items} **/ - #items: InstanceType< - typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items - >[] = []; + #items: MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items + > + > = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.CompatibilityList.Items} @@ -5493,32 +5606,63 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.CompatibilityList.Items} **/ set items( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.CompatibilityList.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.CompatibilityList.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.CompatibilityList.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.CompatibilityList.Items( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.CompatibilityList.Items + >[], ) { this.items = value; return this; @@ -5790,9 +5934,11 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.Description.Sections} **/ - #sections: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Description.Sections - >[] = []; + #sections: MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections + > + > = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.Description.Sections} @@ -5805,30 +5951,63 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.Description.Sections} **/ set sections( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Description.Sections - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.Description.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.Description.Sections(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue as any; + return; } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Description.Sections - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections + >[], ) { this.sections = value; return this; @@ -5841,9 +6020,11 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.Description.Sections.Items} **/ - #items: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items - >[] = []; + #items: MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items + > + > = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.Description.Sections.Items} @@ -5856,32 +6037,63 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.Description.Sections.Items} **/ set items( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.Description.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.Description.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - CreateOfferBasedOnProductActionReq.Description.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.Description.Sections.Items( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.Description.Sections.Items + >[], ) { this.items = value; return this; @@ -8508,9 +8720,9 @@ export class CreateOfferBasedOnProductActionReq { * * @type {CreateOfferBasedOnProductActionReq.TaxSettings.Rates} **/ - #rates: InstanceType< - typeof CreateOfferBasedOnProductActionReq.TaxSettings.Rates - >[] = []; + #rates: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {CreateOfferBasedOnProductActionReq.TaxSettings.Rates} @@ -8523,29 +8735,61 @@ export class CreateOfferBasedOnProductActionReq { * @type {CreateOfferBasedOnProductActionReq.TaxSettings.Rates} **/ set rates( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.TaxSettings.Rates - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.TaxSettings.Rates + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.TaxSettings.Rates + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + CreateOfferBasedOnProductActionReq.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => + new CreateOfferBasedOnProductActionReq.TaxSettings.Rates(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof CreateOfferBasedOnProductActionReq.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => - new CreateOfferBasedOnProductActionReq.TaxSettings.Rates(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates( - value: InstanceType< - typeof CreateOfferBasedOnProductActionReq.TaxSettings.Rates - >[], + value: + | MArray< + InstanceType< + typeof CreateOfferBasedOnProductActionReq.TaxSettings.Rates + > + > + | InstanceType< + typeof CreateOfferBasedOnProductActionReq.TaxSettings.Rates + >[], ) { this.rates = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/EditAnOfferAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/EditAnOfferAction.ts index 8e8638fd..fd861cae 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/EditAnOfferAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/EditAnOfferAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -1448,7 +1441,8 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.ProductSet} **/ - #productSet: InstanceType[] = []; + #productSet: MArray> = + MArray.of([]); /** * * @returns {EditAnOfferActionReq.ProductSet} @@ -1461,23 +1455,46 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.ProductSet} **/ set productSet( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map((item) => new EditAnOfferActionReq.ProductSet(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => new EditAnOfferActionReq.ProductSet(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } - setProductSet(value: InstanceType[]) { + setProductSet( + value: + | MArray> + | InstanceType[], + ) { this.productSet = value; return this; } @@ -1769,7 +1786,8 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.Attachments} **/ - #attachments: InstanceType[] = []; + #attachments: MArray> = + MArray.of([]); /** * * @returns {EditAnOfferActionReq.Attachments} @@ -1782,24 +1800,45 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.Attachments} **/ set attachments( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map((item) => new EditAnOfferActionReq.Attachments(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => new EditAnOfferActionReq.Attachments(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.attachments = value; return this; @@ -2445,8 +2484,9 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.ProductSet.Deposits} **/ - #deposits: InstanceType[] = - []; + #deposits: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionReq.ProductSet.Deposits} @@ -2459,24 +2499,47 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.ProductSet.Deposits} **/ set deposits( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.ProductSet.Deposits(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => new EditAnOfferActionReq.ProductSet.Deposits(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.deposits = value; return this; @@ -2598,9 +2661,9 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.ProductSet.Product.Parameters} **/ - #parameters: InstanceType< - typeof EditAnOfferActionReq.ProductSet.Product.Parameters - >[] = []; + #parameters: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionReq.ProductSet.Product.Parameters} @@ -2613,29 +2676,61 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.ProductSet.Product.Parameters} **/ set parameters( - value: InstanceType< - typeof EditAnOfferActionReq.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionReq.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof EditAnOfferActionReq.ProductSet.Product.Parameters + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionReq.ProductSet.Product.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new EditAnOfferActionReq.ProductSet.Product.Parameters(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.ProductSet.Product.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new EditAnOfferActionReq.ProductSet.Product.Parameters(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue as any; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters( - value: InstanceType< - typeof EditAnOfferActionReq.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionReq.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof EditAnOfferActionReq.ProductSet.Product.Parameters + >[], ) { this.parameters = value; return this; @@ -5893,9 +5988,9 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.CompatibilityList.Items} **/ - #items: InstanceType< - typeof EditAnOfferActionReq.CompatibilityList.Items - >[] = []; + #items: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionReq.CompatibilityList.Items} @@ -5908,28 +6003,51 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.CompatibilityList.Items} **/ set items( - value: InstanceType< - typeof EditAnOfferActionReq.CompatibilityList.Items - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.CompatibilityList.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.CompatibilityList.Items(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.CompatibilityList.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => new EditAnOfferActionReq.CompatibilityList.Items(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof EditAnOfferActionReq.CompatibilityList.Items - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { this.items = value; return this; @@ -6187,9 +6305,9 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.Description.Sections} **/ - #sections: InstanceType< - typeof EditAnOfferActionReq.Description.Sections - >[] = []; + #sections: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionReq.Description.Sections} @@ -6202,24 +6320,47 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.Description.Sections} **/ set sections( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.Description.Sections(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => new EditAnOfferActionReq.Description.Sections(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.sections = value; return this; @@ -6232,9 +6373,9 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.Description.Sections.Items} **/ - #items: InstanceType< - typeof EditAnOfferActionReq.Description.Sections.Items - >[] = []; + #items: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionReq.Description.Sections.Items} @@ -6247,28 +6388,60 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.Description.Sections.Items} **/ set items( - value: InstanceType< - typeof EditAnOfferActionReq.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionReq.Description.Sections.Items + > + > + | InstanceType< + typeof EditAnOfferActionReq.Description.Sections.Items + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.Description.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new EditAnOfferActionReq.Description.Sections.Items(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.Description.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => new EditAnOfferActionReq.Description.Sections.Items(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof EditAnOfferActionReq.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionReq.Description.Sections.Items + > + > + | InstanceType< + typeof EditAnOfferActionReq.Description.Sections.Items + >[], ) { this.items = value; return this; @@ -8798,7 +8971,9 @@ export class EditAnOfferActionReq { * * @type {EditAnOfferActionReq.TaxSettings.Rates} **/ - #rates: InstanceType[] = []; + #rates: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionReq.TaxSettings.Rates} @@ -8811,24 +8986,47 @@ export class EditAnOfferActionReq { * @type {EditAnOfferActionReq.TaxSettings.Rates} **/ set rates( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionReq.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => new EditAnOfferActionReq.TaxSettings.Rates(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionReq.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => new EditAnOfferActionReq.TaxSettings.Rates(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue as any; + return; } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.rates = value; return this; @@ -10643,7 +10841,8 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.ProductSet} **/ - #productSet: InstanceType[] = []; + #productSet: MArray> = + MArray.of([]); /** * * @returns {EditAnOfferActionRes.ProductSet} @@ -10656,23 +10855,46 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.ProductSet} **/ set productSet( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map((item) => new EditAnOfferActionRes.ProductSet(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => new EditAnOfferActionRes.ProductSet(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue as any; + return; } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } - setProductSet(value: InstanceType[]) { + setProductSet( + value: + | MArray> + | InstanceType[], + ) { this.productSet = value; return this; } @@ -11066,7 +11288,8 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Attachments} **/ - #attachments: InstanceType[] = []; + #attachments: MArray> = + MArray.of([]); /** * * @returns {EditAnOfferActionRes.Attachments} @@ -11079,24 +11302,45 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Attachments} **/ set attachments( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map((item) => new EditAnOfferActionRes.Attachments(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => new EditAnOfferActionRes.Attachments(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue as any; + return; } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.attachments = value; return this; @@ -11749,8 +11993,9 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.ProductSet.Deposits} **/ - #deposits: InstanceType[] = - []; + #deposits: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.ProductSet.Deposits} @@ -11763,24 +12008,47 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.ProductSet.Deposits} **/ set deposits( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.ProductSet.Deposits(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => new EditAnOfferActionRes.ProductSet.Deposits(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue as any; + return; } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.deposits = value; return this; @@ -12000,9 +12268,9 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.ProductSet.Product.Parameters} **/ - #parameters: InstanceType< - typeof EditAnOfferActionRes.ProductSet.Product.Parameters - >[] = []; + #parameters: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.ProductSet.Product.Parameters} @@ -12015,29 +12283,61 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.ProductSet.Product.Parameters} **/ set parameters( - value: InstanceType< - typeof EditAnOfferActionRes.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof EditAnOfferActionRes.ProductSet.Product.Parameters + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionRes.ProductSet.Product.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.ProductSet.Product.Parameters(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.ProductSet.Product.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new EditAnOfferActionRes.ProductSet.Product.Parameters(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue as any; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters( - value: InstanceType< - typeof EditAnOfferActionRes.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof EditAnOfferActionRes.ProductSet.Product.Parameters + >[], ) { this.parameters = value; return this; @@ -15078,9 +15378,11 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Publication.Marketplaces.Additional} **/ - #additional: InstanceType< - typeof EditAnOfferActionRes.Publication.Marketplaces.Additional - >[] = []; + #additional: MArray< + InstanceType< + typeof EditAnOfferActionRes.Publication.Marketplaces.Additional + > + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Publication.Marketplaces.Additional} @@ -15093,32 +15395,63 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Publication.Marketplaces.Additional} **/ set additional( - value: InstanceType< - typeof EditAnOfferActionRes.Publication.Marketplaces.Additional - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.Publication.Marketplaces.Additional + > + > + | InstanceType< + typeof EditAnOfferActionRes.Publication.Marketplaces.Additional + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionRes.Publication.Marketplaces.Additional + ) { + this.#additional = MArray.of(value); + } else { + this.#additional = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.Publication.Marketplaces.Additional( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - EditAnOfferActionRes.Publication.Marketplaces.Additional - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additional = value; - } else { - this.#additional = value.map( - (item) => - new EditAnOfferActionRes.Publication.Marketplaces.Additional( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additional = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to additional, because it needs MArray instance or an Array.", + ); } setAdditional( - value: InstanceType< - typeof EditAnOfferActionRes.Publication.Marketplaces.Additional - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.Publication.Marketplaces.Additional + > + > + | InstanceType< + typeof EditAnOfferActionRes.Publication.Marketplaces.Additional + >[], ) { this.additional = value; return this; @@ -16088,9 +16421,11 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons} **/ - #refusalReasons: InstanceType< - typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons - >[] = []; + #refusalReasons: MArray< + InstanceType< + typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons + > + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons} @@ -16103,33 +16438,64 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons} **/ set refusalReasons( - value: InstanceType< - typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons + > + > + | InstanceType< + typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + EditAnOfferActionRes.AdditionalMarketplaces.Publication + .RefusalReasons + ) { + this.#refusalReasons = MArray.of(value); + } else { + this.#refusalReasons = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - EditAnOfferActionRes.AdditionalMarketplaces.Publication - .RefusalReasons - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#refusalReasons = value; - } else { - this.#refusalReasons = value.map( - (item) => - new EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#refusalReasons = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to refusalReasons, because it needs MArray instance or an Array.", + ); } setRefusalReasons( - value: InstanceType< - typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons + > + > + | InstanceType< + typeof EditAnOfferActionRes.AdditionalMarketplaces.Publication.RefusalReasons + >[], ) { this.refusalReasons = value; return this; @@ -17000,7 +17366,9 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Validation.Errors} **/ - #errors: InstanceType[] = []; + #errors: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Validation.Errors} @@ -17013,24 +17381,47 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Validation.Errors} **/ set errors( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Validation.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.Validation.Errors(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Validation.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => new EditAnOfferActionRes.Validation.Errors(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.errors = value; return this; @@ -17039,8 +17430,9 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Validation.Warnings} **/ - #warnings: InstanceType[] = - []; + #warnings: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Validation.Warnings} @@ -17053,24 +17445,47 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Validation.Warnings} **/ set warnings( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Validation.Warnings + ) { + this.#warnings = MArray.of(value); + } else { + this.#warnings = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.Validation.Warnings(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Validation.Warnings - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#warnings = value; - } else { - this.#warnings = value.map( - (item) => new EditAnOfferActionRes.Validation.Warnings(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#warnings = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to warnings, because it needs MArray instance or an Array.", + ); } setWarnings( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.warnings = value; return this; @@ -19907,7 +20322,9 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.TaxSettings.Rates} **/ - #rates: InstanceType[] = []; + #rates: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.TaxSettings.Rates} @@ -19920,24 +20337,47 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.TaxSettings.Rates} **/ set rates( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.TaxSettings.Rates(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => new EditAnOfferActionRes.TaxSettings.Rates(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.rates = value; return this; @@ -20343,9 +20783,9 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Description.Sections} **/ - #sections: InstanceType< - typeof EditAnOfferActionRes.Description.Sections - >[] = []; + #sections: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Description.Sections} @@ -20358,24 +20798,47 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Description.Sections} **/ set sections( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => new EditAnOfferActionRes.Description.Sections(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => new EditAnOfferActionRes.Description.Sections(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.sections = value; return this; @@ -20388,9 +20851,9 @@ export class EditAnOfferActionRes { * * @type {EditAnOfferActionRes.Description.Sections.Items} **/ - #items: InstanceType< - typeof EditAnOfferActionRes.Description.Sections.Items - >[] = []; + #items: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {EditAnOfferActionRes.Description.Sections.Items} @@ -20403,28 +20866,60 @@ export class EditAnOfferActionRes { * @type {EditAnOfferActionRes.Description.Sections.Items} **/ set items( - value: InstanceType< - typeof EditAnOfferActionRes.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.Description.Sections.Items + > + > + | InstanceType< + typeof EditAnOfferActionRes.Description.Sections.Items + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof EditAnOfferActionRes.Description.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new EditAnOfferActionRes.Description.Sections.Items(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof EditAnOfferActionRes.Description.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => new EditAnOfferActionRes.Description.Sections.Items(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof EditAnOfferActionRes.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof EditAnOfferActionRes.Description.Sections.Items + > + > + | InstanceType< + typeof EditAnOfferActionRes.Description.Sections.Items + >[], ) { this.items = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.ts index 6c9027c8..104462f9 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetAllAvailableOfferPromotionPackagesAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -216,9 +209,11 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.BasePackages} **/ - #basePackages: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages - >[] = []; + #basePackages: MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages + > + > = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.BasePackages} @@ -231,30 +226,63 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.BasePackages} **/ set basePackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes.BasePackages + ) { + this.#basePackages = MArray.of(value); + } else { + this.#basePackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.BasePackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.BasePackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#basePackages = value; - } else { - this.#basePackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.BasePackages(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#basePackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to basePackages, because it needs MArray instance or an Array.", + ); } setBasePackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.BasePackages + >[], ) { this.basePackages = value; return this; @@ -263,9 +291,11 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages + > + > = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages} @@ -278,32 +308,63 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.ExtraPackages + >[], ) { this.extraPackages = value; return this; @@ -312,9 +373,11 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[] = []; + #additionalMarketplaces: MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces} @@ -327,32 +390,63 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue as any; + return; } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces + >[], ) { this.additionalMarketplaces = value; return this; @@ -752,9 +846,11 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages} **/ - #basePackages: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages - >[] = []; + #basePackages: MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages + > + > = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages} @@ -767,33 +863,64 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages} **/ set basePackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes + .AdditionalMarketplaces.BasePackages + ) { + this.#basePackages = MArray.of(value); + } else { + this.#basePackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - .BasePackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#basePackages = value; - } else { - this.#basePackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#basePackages = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to basePackages, because it needs MArray instance or an Array.", + ); } setBasePackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.BasePackages + >[], ) { this.basePackages = value; return this; @@ -802,9 +929,11 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > = MArray.of([]); /** * * @returns {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} @@ -817,33 +946,64 @@ export class GetAllAvailableOfferPromotionPackagesActionRes { * @type {GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllAvailableOfferPromotionPackagesActionRes + .AdditionalMarketplaces.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof GetAllAvailableOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + >[], ) { this.extraPackages = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOfferPromotionPackagesAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOfferPromotionPackagesAction.ts index 10ba30d4..a0de542d 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOfferPromotionPackagesAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOfferPromotionPackagesAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -343,9 +336,9 @@ export class GetOfferPromotionPackagesActionRes { * * @type {GetOfferPromotionPackagesActionRes.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof GetOfferPromotionPackagesActionRes.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {GetOfferPromotionPackagesActionRes.ExtraPackages} @@ -358,28 +351,52 @@ export class GetOfferPromotionPackagesActionRes { * @type {GetOfferPromotionPackagesActionRes.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof GetOfferPromotionPackagesActionRes.ExtraPackages - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetOfferPromotionPackagesActionRes.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetOfferPromotionPackagesActionRes.ExtraPackages(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetOfferPromotionPackagesActionRes.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => new GetOfferPromotionPackagesActionRes.ExtraPackages(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof GetOfferPromotionPackagesActionRes.ExtraPackages - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { this.extraPackages = value; return this; @@ -427,9 +444,11 @@ export class GetOfferPromotionPackagesActionRes { * * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces: InstanceType< - typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[] = []; + #additionalMarketplaces: MArray< + InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > = MArray.of([]); /** * * @returns {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces} @@ -442,30 +461,63 @@ export class GetOfferPromotionPackagesActionRes { * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces( - value: InstanceType< - typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferPromotionPackagesActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue as any; + return; } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces( - value: InstanceType< - typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + >[], ) { this.additionalMarketplaces = value; return this; @@ -1339,9 +1391,11 @@ export class GetOfferPromotionPackagesActionRes { * * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > = MArray.of([]); /** * * @returns {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} @@ -1354,33 +1408,64 @@ export class GetOfferPromotionPackagesActionRes { * @type {GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferPromotionPackagesActionRes.AdditionalMarketplaces + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferPromotionPackagesActionRes.AdditionalMarketplaces - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof GetOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + >[], ) { this.extraPackages = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOffersWithMissingParametersAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOffersWithMissingParametersAction.ts index 5121df77..a6958d42 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOffersWithMissingParametersAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetOffersWithMissingParametersAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -140,9 +133,9 @@ export class GetOffersWithMissingParametersActionRes { * * @type {GetOffersWithMissingParametersActionRes.Offers} **/ - #offers: InstanceType< - typeof GetOffersWithMissingParametersActionRes.Offers - >[] = []; + #offers: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {GetOffersWithMissingParametersActionRes.Offers} @@ -155,28 +148,51 @@ export class GetOffersWithMissingParametersActionRes { * @type {GetOffersWithMissingParametersActionRes.Offers} **/ set offers( - value: InstanceType< - typeof GetOffersWithMissingParametersActionRes.Offers - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetOffersWithMissingParametersActionRes.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map( + (item) => new GetOffersWithMissingParametersActionRes.Offers(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetOffersWithMissingParametersActionRes.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => new GetOffersWithMissingParametersActionRes.Offers(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue as any; + return; } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } setOffers( - value: InstanceType< - typeof GetOffersWithMissingParametersActionRes.Offers - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { this.offers = value; return this; @@ -266,9 +282,11 @@ export class GetOffersWithMissingParametersActionRes { * * @type {GetOffersWithMissingParametersActionRes.Offers.Parameters} **/ - #parameters: InstanceType< - typeof GetOffersWithMissingParametersActionRes.Offers.Parameters - >[] = []; + #parameters: MArray< + InstanceType< + typeof GetOffersWithMissingParametersActionRes.Offers.Parameters + > + > = MArray.of([]); /** * * @returns {GetOffersWithMissingParametersActionRes.Offers.Parameters} @@ -281,30 +299,63 @@ export class GetOffersWithMissingParametersActionRes { * @type {GetOffersWithMissingParametersActionRes.Offers.Parameters} **/ set parameters( - value: InstanceType< - typeof GetOffersWithMissingParametersActionRes.Offers.Parameters - >[], + value: + | MArray< + InstanceType< + typeof GetOffersWithMissingParametersActionRes.Offers.Parameters + > + > + | InstanceType< + typeof GetOffersWithMissingParametersActionRes.Offers.Parameters + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOffersWithMissingParametersActionRes.Offers.Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new GetOffersWithMissingParametersActionRes.Offers.Parameters( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOffersWithMissingParametersActionRes.Offers.Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new GetOffersWithMissingParametersActionRes.Offers.Parameters(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue as any; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters( - value: InstanceType< - typeof GetOffersWithMissingParametersActionRes.Offers.Parameters - >[], + value: + | MArray< + InstanceType< + typeof GetOffersWithMissingParametersActionRes.Offers.Parameters + > + > + | InstanceType< + typeof GetOffersWithMissingParametersActionRes.Offers.Parameters + >[], ) { this.parameters = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.ts index d71e2904..c962aa47 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/GetPromoOptionsForSellerSOffersAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -278,9 +271,9 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions} **/ - #promoOptions: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions - >[] = []; + #promoOptions: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions} @@ -293,29 +286,61 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions} **/ set promoOptions( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions + ) { + this.#promoOptions = MArray.of(value); + } else { + this.#promoOptions = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetPromoOptionsForSellerSOffersActionRes.PromoOptions - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#promoOptions = value; - } else { - this.#promoOptions = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#promoOptions = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to promoOptions, because it needs MArray instance or an Array.", + ); } setPromoOptions( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions + >[], ) { this.promoOptions = value; return this; @@ -472,9 +497,11 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages + > + > = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages} @@ -487,32 +514,63 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.ExtraPackages + >[], ) { this.extraPackages = value; return this; @@ -565,9 +623,11 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces} **/ - #additionalMarketplaces: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces - >[] = []; + #additionalMarketplaces: MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces + > + > = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces} @@ -580,33 +640,64 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces} **/ set additionalMarketplaces( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions + .AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetPromoOptionsForSellerSOffersActionRes.PromoOptions - .AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue as any; + return; } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces + >[], ) { this.additionalMarketplaces = value; return this; @@ -1488,9 +1579,11 @@ export class GetPromoOptionsForSellerSOffersActionRes { * * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages + > + > = MArray.of([]); /** * * @returns {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages} @@ -1503,33 +1596,64 @@ export class GetPromoOptionsForSellerSOffersActionRes { * @type {GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetPromoOptionsForSellerSOffersActionRes.PromoOptions + .AdditionalMarketplaces.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetPromoOptionsForSellerSOffersActionRes.PromoOptions - .AdditionalMarketplaces.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof GetPromoOptionsForSellerSOffersActionRes.PromoOptions.AdditionalMarketplaces.ExtraPackages + >[], ) { this.extraPackages = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandDetailedResultAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandDetailedResultAction.ts index 64c9e437..a5bb814c 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandDetailedResultAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandDetailedResultAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -239,9 +232,9 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.Tasks} **/ - #tasks: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Tasks - >[] = []; + #tasks: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.Tasks} @@ -254,28 +247,52 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.Tasks} **/ set tasks( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Tasks - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof ModificationCommandDetailedResultActionRes.Tasks + ) { + this.#tasks = MArray.of(value); + } else { + this.#tasks = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.Tasks(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModificationCommandDetailedResultActionRes.Tasks - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#tasks = value; - } else { - this.#tasks = value.map( - (item) => new ModificationCommandDetailedResultActionRes.Tasks(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#tasks = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to tasks, because it needs MArray instance or an Array.", + ); } setTasks( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Tasks - >[], + value: + | MArray< + InstanceType + > + | InstanceType[], ) { this.tasks = value; return this; @@ -325,9 +342,11 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces: InstanceType< - typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces - >[] = []; + #additionalMarketplaces: MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + > + > = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces} @@ -340,32 +359,63 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue as any; + return; } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + >[], ) { this.additionalMarketplaces = value; return this; @@ -511,9 +561,11 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.Tasks.Errors} **/ - #errors: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Tasks.Errors - >[] = []; + #errors: MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.Tasks.Errors + > + > = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.Tasks.Errors} @@ -526,30 +578,63 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.Tasks.Errors} **/ set errors( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Tasks.Errors - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.Tasks.Errors + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.Tasks.Errors + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.Tasks.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.Tasks.Errors( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.Tasks.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.Tasks.Errors(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue as any; + return; } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Tasks.Errors - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.Tasks.Errors + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.Tasks.Errors + >[], ) { this.errors = value; return this; @@ -1322,9 +1407,11 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.Modification.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages + > + > = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.Modification.ExtraPackages} @@ -1337,32 +1424,64 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.Modification.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.Modification + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.Modification.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.Modification.ExtraPackages( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.Modification.ExtraPackages + >[], ) { this.extraPackages = value; return this; @@ -1907,9 +2026,11 @@ export class ModificationCommandDetailedResultActionRes { * * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages + > + > = MArray.of([]); /** * * @returns {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages} @@ -1922,33 +2043,64 @@ export class ModificationCommandDetailedResultActionRes { * @type {ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModificationCommandDetailedResultActionRes.AdditionalMarketplaces + .Modification.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModificationCommandDetailedResultActionRes.AdditionalMarketplaces - .Modification.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages + > + > + | InstanceType< + typeof ModificationCommandDetailedResultActionRes.AdditionalMarketplaces.Modification.ExtraPackages + >[], ) { this.extraPackages = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandSummaryAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandSummaryAction.ts index c37146d1..727f96bf 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandSummaryAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModificationCommandSummaryAction.ts @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.ts index 5764ae3e..df1b87b4 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyOfferPromotionPackagesAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -318,9 +311,9 @@ export class ModifyOfferPromotionPackagesActionReq { * * @type {ModifyOfferPromotionPackagesActionReq.Modifications} **/ - #modifications: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.Modifications - >[] = []; + #modifications: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionReq.Modifications} @@ -333,28 +326,60 @@ export class ModifyOfferPromotionPackagesActionReq { * @type {ModifyOfferPromotionPackagesActionReq.Modifications} **/ set modifications( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.Modifications - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.Modifications + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.Modifications + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof ModifyOfferPromotionPackagesActionReq.Modifications + ) { + this.#modifications = MArray.of(value); + } else { + this.#modifications = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionReq.Modifications(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModifyOfferPromotionPackagesActionReq.Modifications - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#modifications = value; - } else { - this.#modifications = value.map( - (item) => new ModifyOfferPromotionPackagesActionReq.Modifications(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#modifications = mcastValue as any; + return; } + console.warn( + "Cannot assing value to modifications, because it needs MArray instance or an Array.", + ); } setModifications( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.Modifications - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.Modifications + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.Modifications + >[], ) { this.modifications = value; return this; @@ -363,9 +388,11 @@ export class ModifyOfferPromotionPackagesActionReq { * * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces} **/ - #additionalMarketplaces: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces - >[] = []; + #additionalMarketplaces: MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + > + > = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces} @@ -378,32 +405,63 @@ export class ModifyOfferPromotionPackagesActionReq { * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces} **/ set additionalMarketplaces( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + >[], ) { this.additionalMarketplaces = value; return this; @@ -621,9 +679,11 @@ export class ModifyOfferPromotionPackagesActionReq { * * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications} **/ - #modifications: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications - >[] = []; + #modifications: MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications + > + > = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications} @@ -636,33 +696,64 @@ export class ModifyOfferPromotionPackagesActionReq { * @type {ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications} **/ set modifications( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces + .Modifications + ) { + this.#modifications = MArray.of(value); + } else { + this.#modifications = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces - .Modifications - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#modifications = value; - } else { - this.#modifications = value.map( - (item) => - new ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#modifications = mcastValue as any; + return; } + console.warn( + "Cannot assing value to modifications, because it needs MArray instance or an Array.", + ); } setModifications( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionReq.AdditionalMarketplaces.Modifications + >[], ) { this.modifications = value; return this; @@ -1240,9 +1331,9 @@ export class ModifyOfferPromotionPackagesActionRes { * * @type {ModifyOfferPromotionPackagesActionRes.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionRes.ExtraPackages} @@ -1255,28 +1346,60 @@ export class ModifyOfferPromotionPackagesActionRes { * @type {ModifyOfferPromotionPackagesActionRes.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.ExtraPackages + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof ModifyOfferPromotionPackagesActionRes.ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionRes.ExtraPackages(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModifyOfferPromotionPackagesActionRes.ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => new ModifyOfferPromotionPackagesActionRes.ExtraPackages(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.ExtraPackages + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.ExtraPackages + >[], ) { this.extraPackages = value; return this; @@ -1324,9 +1447,11 @@ export class ModifyOfferPromotionPackagesActionRes { * * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ - #additionalMarketplaces: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[] = []; + #additionalMarketplaces: MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces} @@ -1339,32 +1464,63 @@ export class ModifyOfferPromotionPackagesActionRes { * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces} **/ set additionalMarketplaces( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + ) { + this.#additionalMarketplaces = MArray.of(value); + } else { + this.#additionalMarketplaces = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additionalMarketplaces = value; - } else { - this.#additionalMarketplaces = value.map( - (item) => - new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additionalMarketplaces = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to additionalMarketplaces, because it needs MArray instance or an Array.", + ); } setAdditionalMarketplaces( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + >[], ) { this.additionalMarketplaces = value; return this; @@ -2244,9 +2400,11 @@ export class ModifyOfferPromotionPackagesActionRes { * * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ - #extraPackages: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[] = []; + #extraPackages: MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > = MArray.of([]); /** * * @returns {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} @@ -2259,33 +2417,64 @@ export class ModifyOfferPromotionPackagesActionRes { * @type {ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages} **/ set extraPackages( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces + .ExtraPackages + ) { + this.#extraPackages = MArray.of(value); + } else { + this.#extraPackages = MArray.of( + value.map( + (item) => + new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces - .ExtraPackages - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#extraPackages = value; - } else { - this.#extraPackages = value.map( - (item) => - new ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#extraPackages = mcastValue as any; + return; } + console.warn( + "Cannot assing value to extraPackages, because it needs MArray instance or an Array.", + ); } setExtraPackages( - value: InstanceType< - typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages - >[], + value: + | MArray< + InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + > + > + | InstanceType< + typeof ModifyOfferPromotionPackagesActionRes.AdditionalMarketplaces.ExtraPackages + >[], ) { this.extraPackages = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.ts index a4655436..9cd8e8a0 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/ModifyTheBuyNowPriceInAnOfferAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -1171,9 +1164,9 @@ export class ModifyTheBuyNowPriceInAnOfferActionRes { * * @type {ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors} **/ - #errors: InstanceType< - typeof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors - >[] = []; + #errors: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors} @@ -1186,29 +1179,61 @@ export class ModifyTheBuyNowPriceInAnOfferActionRes { * @type {ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors} **/ set errors( - value: InstanceType< - typeof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors - >[], + value: + | MArray< + InstanceType< + typeof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors + > + > + | InstanceType< + typeof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors( - value: InstanceType< - typeof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors - >[], + value: + | MArray< + InstanceType< + typeof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors + > + > + | InstanceType< + typeof ModifyTheBuyNowPriceInAnOfferActionRes.Output.Errors + >[], ) { this.errors = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandDetailedReportAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandDetailedReportAction.ts index c1bf71c7..89a2979b 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandDetailedReportAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandDetailedReportAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -166,8 +159,9 @@ export class PublishCommandDetailedReportActionRes { * * @type {PublishCommandDetailedReportActionRes.Tasks} **/ - #tasks: InstanceType[] = - []; + #tasks: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {PublishCommandDetailedReportActionRes.Tasks} @@ -180,24 +174,47 @@ export class PublishCommandDetailedReportActionRes { * @type {PublishCommandDetailedReportActionRes.Tasks} **/ set tasks( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof PublishCommandDetailedReportActionRes.Tasks + ) { + this.#tasks = MArray.of(value); + } else { + this.#tasks = MArray.of( + value.map( + (item) => new PublishCommandDetailedReportActionRes.Tasks(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof PublishCommandDetailedReportActionRes.Tasks - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#tasks = value; - } else { - this.#tasks = value.map( - (item) => new PublishCommandDetailedReportActionRes.Tasks(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#tasks = mcastValue as any; + return; } + console.warn( + "Cannot assing value to tasks, because it needs MArray instance or an Array.", + ); } setTasks( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.tasks = value; return this; @@ -319,9 +336,9 @@ export class PublishCommandDetailedReportActionRes { * * @type {PublishCommandDetailedReportActionRes.Tasks.Errors} **/ - #errors: InstanceType< - typeof PublishCommandDetailedReportActionRes.Tasks.Errors - >[] = []; + #errors: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {PublishCommandDetailedReportActionRes.Tasks.Errors} @@ -334,29 +351,60 @@ export class PublishCommandDetailedReportActionRes { * @type {PublishCommandDetailedReportActionRes.Tasks.Errors} **/ set errors( - value: InstanceType< - typeof PublishCommandDetailedReportActionRes.Tasks.Errors - >[], + value: + | MArray< + InstanceType< + typeof PublishCommandDetailedReportActionRes.Tasks.Errors + > + > + | InstanceType< + typeof PublishCommandDetailedReportActionRes.Tasks.Errors + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof PublishCommandDetailedReportActionRes.Tasks.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new PublishCommandDetailedReportActionRes.Tasks.Errors(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof PublishCommandDetailedReportActionRes.Tasks.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new PublishCommandDetailedReportActionRes.Tasks.Errors(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue as any; + return; } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors( - value: InstanceType< - typeof PublishCommandDetailedReportActionRes.Tasks.Errors - >[], + value: + | MArray< + InstanceType< + typeof PublishCommandDetailedReportActionRes.Tasks.Errors + > + > + | InstanceType< + typeof PublishCommandDetailedReportActionRes.Tasks.Errors + >[], ) { this.errors = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandSummaryAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandSummaryAction.ts index e37a01cf..67865e4c 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandSummaryAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-management/PublishCommandSummaryAction.ts @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/buildUrl.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/buildUrl.ts deleted file mode 100644 index cf08f1cc..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/buildUrl.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Handy tool to create a final callable url, from query string, query params, - * and the actual url. - * @param template - * @param params - * @param qs - * @returns - */ -export function buildUrl( - url: string, - params?: Record, - qs?: URLSearchParams -) { - // Replace :placeholders - if (params) { - Object.entries(params as Record).forEach(([key, value]) => { - url = url.replace( - new RegExp(`:${key}`, "g"), - encodeURIComponent(String(value)) - ); - }); - } - - if (qs && qs instanceof URLSearchParams) { - url += `?${qs.toString()}`; - } else if (qs && Object.keys(qs).length) { - const query = new URLSearchParams( - Object.entries(qs).map(([k, v]) => [k, String(v)]) - ).toString(); - url += `?${query}`; - } - - return url; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/fetchx.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/fetchx.ts deleted file mode 100644 index 774f16b0..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/fetchx.ts +++ /dev/null @@ -1,196 +0,0 @@ -export type TypedRequestInit = Omit< - RequestInit, - "body" | "headers" -> & { - body?: TBody; - headers?: THeaders; -}; -export class TypedResponse extends Response { - override json(): Promise { - return super.json(); - } - result: - | T - | undefined - | ReadableStream> - | null - | string; -} -export async function fetchx< - TResponse = unknown, - TBody = unknown, - THeaders = unknown, ->( - input: RequestInfo | URL, - init?: TypedRequestInit, - ctx?: FetchxContext | null, -): Promise> { - let url = input.toString(); - let reqInit: TypedRequestInit = init || {}; - let res: TypedResponse; - let fetchFn = fetch; - - if (ctx) { - [url, reqInit] = await ctx.apply(url, reqInit); - - if (ctx.fetchOverrideFn) { - fetchFn = ctx.fetchOverrideFn; - } - } - - res = (await fetchFn( - url, - reqInit as RequestInit, - )) as TypedResponse; - - if (ctx) { - res = await ctx.handle(res); - } - return res; -} -type DtoFactory = { new (data: any): T } | ((data: any) => T); -function isConstructor(fn: DtoFactory): fn is { new (data: any): T } { - return ( - typeof fn === "function" && fn.prototype && fn.prototype.constructor === fn - ); -} -export async function handleFetchResponse( - res: TypedResponse, - dto?: DtoFactory, - onMessage?: (msg: any) => void, - signal?: AbortSignal | null, -): Promise<{ done: Promise; response: TypedResponse }> { - const ct = res.headers.get("content-type") || ""; - const cd = res.headers.get("content-disposition") || ""; - if (ct.includes("text/event-stream")) { - return SSEFetch(res, onMessage, signal); - } - if ( - cd.includes("attachment") || - (!ct.includes("json") && !ct.startsWith("text/")) - ) { - (res as any).result = res.body; - } else if (ct.includes("application/json")) { - const json = await res.json(); - if (dto) { - if (isConstructor(dto)) { - (res as any).result = new dto(json); // ✅ class constructor - } else { - (res as any).result = dto(json); // ✅ factory function - } - } else { - (res as any).result = json; - } - } else { - (res as any).result = await res.text(); - } - return { done: Promise.resolve(), response: res as any }; -} -export const SSEFetch = ( - res: TypedResponse, - onMessage?: (ev: MessageEvent) => void, - signal?: AbortSignal | null, -): { response: TypedResponse; done: Promise } => { - if (!res.body) throw new Error("SSE requires readable body"); - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - const done = new Promise((resolve, reject) => { - function readChunk() { - reader - .read() - .then(({ done: finished, value }) => { - if (signal?.aborted) { - reader.cancel(); - return resolve(); // resolve on abort - } - if (finished) return resolve(); // normal end - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split("\n\n"); - buffer = parts.pop() || ""; - for (const part of parts) { - let data = ""; - let event = "message"; - part.split("\n").forEach((line) => { - if (line.startsWith("data:")) data += line.slice(5).trim(); - else if (line.startsWith("event:")) event = line.slice(6).trim(); - }); - if (data) { - if (data === "[DONE]") return resolve(); - onMessage?.(new MessageEvent(event, { data })); - } - } - readChunk(); - }) - .catch((err) => { - if (err.name === "AbortError") resolve(); - else reject(err); - }); - } - readChunk(); - }); - return { response: res, done }; -}; -export class FetchxContext { - constructor( - public baseUrl: string = "", - public defaultHeaders: Record = {}, - public requestInterceptor?: ( - url: string, - init: TypedRequestInit, - ) => - | Promise<[string, TypedRequestInit]> - | [string, TypedRequestInit], - public responseInterceptor?: ( - res: TypedResponse, - ) => Promise>, - /** - * Overrides the browser fetch function, for different purposes. It would recieve the same first 2 arguments as fetch, - * as well as third one of fetchx context. If you pass the fetch itself to override, it should have no effect. - */ - public fetchOverrideFn?: ( - input: RequestInfo | URL, - init?: TypedRequestInit, - ) => Promise, - ) {} - async apply( - url: string, - init: TypedRequestInit, - ): Promise<[string, TypedRequestInit]> { - // prefix baseUrl - if (!/^https?:\/\//.test(url)) { - url = this.baseUrl + url; - } - // merge default headers - (init.headers as unknown) = { - ...this.defaultHeaders, - ...((init.headers as object) || {}), - }; - // call request interceptor if present - if (this.requestInterceptor) { - return this.requestInterceptor(url, init); - } - return [url, init]; - } - async handle(res: TypedResponse): Promise> { - if (this.responseInterceptor) { - return this.responseInterceptor(res); - } - return res; - } - clone(overrides?: Partial): FetchxContext { - return new FetchxContext( - overrides?.baseUrl ?? this.baseUrl, - { ...this.defaultHeaders, ...(overrides?.defaultHeaders || {}) }, - overrides?.requestInterceptor ?? this.requestInterceptor, - overrides?.responseInterceptor ?? this.responseInterceptor, - ); - } -} -export type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; \ No newline at end of file diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/operators.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/operators.ts deleted file mode 100644 index 728da07e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/operators.ts +++ /dev/null @@ -1,173 +0,0 @@ -export class MOne { - private operation: string | null = null; - private selector: S | undefined; - - private content: T | undefined = undefined; - - isNull(): boolean { - return this.content === null; - } - - isSelector(): boolean { - return this.selector !== undefined && this.operation !== null; - } - - get(): T { - return this.content!; - } - - static of(value: T) { - const one = new MOne(); - one.content = value; - - return one; - } - - static select(selector: any) { - const one = new MOne(); - one.selector = selector; - one.operation = "replace"; - - return one; - } - - toJSON() { - // When its explicit replace, it means that we need to pass a selector, so reader will - // be able to replace it via internal mechanism - if (this.operation === "replace") { - return { - __operation: this.operation, - selector: this.selector, - }; - } - - return this.content; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, maybe just giving back one is enough. -export class MOneNullable extends MOne {} - -// Array describes how an incoming list should be applied to an existing one, -// mirroring emigo.Array on the Go side. It lets a PATCH-style payload say -// "replace the whole set" versus "append to the existing set". -// -// On the wire a "replace" is implicit (a bare array), while an "append" is -// tagged with __operation so the reader keeps the existing rows. This keeps -// the payload identical to the Go client/backend generators. -export class MArray { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "replace"; - - return arr; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "append"; - - return arr; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Array is enough. -export class MArrayNullable extends Array {} - -// Collection mirrors emigo.Collection on the Go side. Structurally it is the -// same as Array — a list carrying a "replace"/"append" operation — but it is a -// distinct field type: a collection holds a list of a target entity, whereas an -// array holds a list of an inline DTO. -export class MCollection { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "replace"; - - return collection; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "append"; - - return collection; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Collection is enough. -export class CollectionNullable extends MCollection {} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/withPrefix.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts deleted file mode 100644 index 850d7626..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/common/EnvelopeClass.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * To declare a new envelope class, you must follow these rules: - * 1. The constructor must accept any object, which will contain the parsed JSON message - * from a response. - * 2. Envelope classes must provide a function to update the payload. Since payloads are - * type-safe, they must be instantiated and passed to the envelope; the common constructor - * alone is not enough. - * 3. Enveope must have a way to provide the content back actually, in order to create a class out of them. - */ - -export type CreatorSignature = (item: unknown) => T; - -export interface EnvelopeClass { - setCreator(fn: CreatorSignature): this; - inject(data: unknown): this; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts deleted file mode 100644 index 455cdd2e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/flat-array/FlatArray.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; - -// Some responses are returning a flat array, without any other information -// regarding the pagination, etc. They start [{},{}...] style. -// For those which might have a single project which is array but none-standard, -// Use CaptureArray instead. - -export class FlatArray implements EnvelopeClass { - public data: T[] = []; - creator?: CreatorSignature | null = null; - - inject(data: unknown) { - if (!Array.isArray(data)) { - throw new Error( - "FlatArray can only work on flat array items, such as [{},...], and doesn't accept any other type" - ); - } - - if (typeof this.creator !== "undefined") { - this.data = data.map((item) => - (this.creator as CreatorSignature)(item) - ); - } else { - this.data = data; - } - - return this; - } - - setCreator(creator: CreatorSignature) { - this.creator = creator; - - return this; - } - - // Implement thigs here, which would make the flat array to act as an array actually, how can it become - // class instance as an array? -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts deleted file mode 100644 index 0c078ce3..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts +++ /dev/null @@ -1,1715 +0,0 @@ -import { withPrefix } from "./sdk/common/withPrefix"; -/** - * The base class definition for responseDto - **/ -export class ResponseDto { - /** - * Version of the API used for this response. - * @type {string} - **/ - #apiVersion?: string | null = undefined; - /** - * Version of the API used for this response. - * @returns {string} - **/ - get apiVersion() { - return this.#apiVersion; - } - /** - * Version of the API used for this response. - * @type {string} - **/ - set apiVersion(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#apiVersion = correctType ? value : String(value); - } - setApiVersion(value: string | null | undefined) { - this.apiVersion = value; - return this; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - #context?: string | null = undefined; - /** - * Context string provided by the client or system for request tracking. - * @returns {string} - **/ - get context() { - return this.#context; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - set context(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#context = correctType ? value : String(value); - } - setContext(value: string | null | undefined) { - this.context = value; - return this; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier assigned to the request/response. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - #method?: string | null = undefined; - /** - * Name of the API method invoked. - * @returns {string} - **/ - get method() { - return this.#method; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - set method(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#method = correctType ? value : String(value); - } - setMethod(value: string | null | undefined) { - this.method = value; - return this; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - #params: any = null; - /** - * Parameters sent with the request. - * @returns {any} - **/ - get params() { - return this.#params; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - set params(value: any) { - this.#params = value; - } - setParams(value: any) { - this.params = value; - return this; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - #data!: InstanceType>; - /** - * Main data payload of the response. - * @returns {ResponseDto.Data} - **/ - get data() { - return this.#data; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - set data(value: InstanceType>) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Data) { - this.#data = value; - } else { - this.#data = new ResponseDto.Data(value); - } - } - setData(value: InstanceType>) { - this.data = value; - return this; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - #error!: InstanceType; - /** - * Error details, if the request failed. - * @returns {ResponseDto.Error} - **/ - get error() { - return this.#error; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - set error(value: InstanceType) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Error) { - this.#error = value; - } else { - this.#error = new ResponseDto.Error(value); - } - } - setError(value: InstanceType) { - this.error = value; - return this; - } - /** - * The base class definition for data - **/ - static Data = class Data { - /** - * Single item returned by the API. - * @type {any} - **/ - #item: T | null = null; - /** - * Single item returned by the API. - * @returns {T} - **/ - get item(): T | null { - return this.#item; - } - /** - * Single item returned by the API. - * @type {any} - **/ - set item(value: any) { - this.#item = value; - } - setItem(value: any) { - this.item = value; - return this; - } - /** - * List of items returned by the API. - * @type {any} - **/ - #items: T[] = []; - /** - * List of items returned by the API. - * @returns {T[]} - **/ - get items(): T[] { - return this.#items; - } - /** - * List of items returned by the API. - * @type {T[]} - **/ - set items(value: T[]) { - this.#items = value; - } - setItems(value: T[]) { - this.items = value; - return this; - } - /** - * Link to edit this resource. - * @type {string} - **/ - #editLink?: string | null = undefined; - /** - * Link to edit this resource. - * @returns {string} - **/ - get editLink() { - return this.#editLink; - } - /** - * Link to edit this resource. - * @type {string} - **/ - set editLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#editLink = correctType ? value : String(value); - } - setEditLink(value: string | null | undefined) { - this.editLink = value; - return this; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - #selfLink?: string | null = undefined; - /** - * Link to retrieve this resource. - * @returns {string} - **/ - get selfLink() { - return this.#selfLink; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - set selfLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#selfLink = correctType ? value : String(value); - } - setSelfLink(value: string | null | undefined) { - this.selfLink = value; - return this; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - #kind?: string | null = undefined; - /** - * Resource type (kind) identifier. - * @returns {string} - **/ - get kind() { - return this.#kind; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - set kind(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#kind = correctType ? value : String(value); - } - setKind(value: string | null | undefined) { - this.kind = value; - return this; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - #fields?: string | null = undefined; - /** - * Selector specifying which fields are included in a partial response. - * @returns {string} - **/ - get fields() { - return this.#fields; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - set fields(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#fields = correctType ? value : String(value); - } - setFields(value: string | null | undefined) { - this.fields = value; - return this; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - #etag?: string | null = undefined; - /** - * ETag of the resource, used for caching/version control. - * @returns {string} - **/ - get etag() { - return this.#etag; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - set etag(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#etag = correctType ? value : String(value); - } - setEtag(value: string | null | undefined) { - this.etag = value; - return this; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - #cursor?: string | null = undefined; - /** - * Cursor for paginated data fetching. - * @returns {string} - **/ - get cursor() { - return this.#cursor; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - set cursor(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#cursor = correctType ? value : String(value); - } - setCursor(value: string | null | undefined) { - this.cursor = value; - return this; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier of the resource. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Language code of the response data. - * @type {string} - **/ - #lang?: string | null = undefined; - /** - * Language code of the response data. - * @returns {string} - **/ - get lang() { - return this.#lang; - } - /** - * Language code of the response data. - * @type {string} - **/ - set lang(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#lang = correctType ? value : String(value); - } - setLang(value: string | null | undefined) { - this.lang = value; - return this; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - #updated?: string | null = undefined; - /** - * Last modification time of the resource. - * @returns {string} - **/ - get updated() { - return this.#updated; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - set updated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#updated = correctType ? value : String(value); - } - setUpdated(value: string | null | undefined) { - this.updated = value; - return this; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - #currentItemCount?: number | null = undefined; - /** - * Number of items in the current response page. - * @returns {number} - **/ - get currentItemCount() { - return this.#currentItemCount; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - set currentItemCount(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#currentItemCount = parsedValue; - } - } - setCurrentItemCount(value: number | null | undefined) { - this.currentItemCount = value; - return this; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - #itemsPerPage?: number | null = undefined; - /** - * Maximum number of items per page. - * @returns {number} - **/ - get itemsPerPage() { - return this.#itemsPerPage; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - set itemsPerPage(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#itemsPerPage = parsedValue; - } - } - setItemsPerPage(value: number | null | undefined) { - this.itemsPerPage = value; - return this; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - #startIndex?: number | null = undefined; - /** - * Index of the first item in the current page. - * @returns {number} - **/ - get startIndex() { - return this.#startIndex; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - set startIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#startIndex = parsedValue; - } - } - setStartIndex(value: number | null | undefined) { - this.startIndex = value; - return this; - } - /** - * Total number of items available. - * @type {number} - **/ - #totalItems?: number | null = undefined; - /** - * Total number of items available. - * @returns {number} - **/ - get totalItems() { - return this.#totalItems; - } - /** - * Total number of items available. - * @type {number} - **/ - set totalItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalItems = parsedValue; - } - } - setTotalItems(value: number | null | undefined) { - this.totalItems = value; - return this; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - #totalAvailableItems?: number | null = undefined; - /** - * Number of items available for this user/query. - * @returns {number} - **/ - get totalAvailableItems() { - return this.#totalAvailableItems; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - set totalAvailableItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalAvailableItems = parsedValue; - } - } - setTotalAvailableItems(value: number | null | undefined) { - this.totalAvailableItems = value; - return this; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - #pageIndex?: number | null = undefined; - /** - * Current page index in the pagination. - * @returns {number} - **/ - get pageIndex() { - return this.#pageIndex; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - set pageIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#pageIndex = parsedValue; - } - } - setPageIndex(value: number | null | undefined) { - this.pageIndex = value; - return this; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - #totalPages?: number | null = undefined; - /** - * Total number of pages in the pagination. - * @returns {number} - **/ - get totalPages() { - return this.#totalPages; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - set totalPages(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalPages = parsedValue; - } - } - setTotalPages(value: number | null | undefined) { - this.totalPages = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.item !== undefined) { - this.item = d.item; - } - if (d.items !== undefined) { - this.items = d.items; - } - if (d.editLink !== undefined) { - this.editLink = d.editLink; - } - if (d.selfLink !== undefined) { - this.selfLink = d.selfLink; - } - if (d.kind !== undefined) { - this.kind = d.kind; - } - if (d.fields !== undefined) { - this.fields = d.fields; - } - if (d.etag !== undefined) { - this.etag = d.etag; - } - if (d.cursor !== undefined) { - this.cursor = d.cursor; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.lang !== undefined) { - this.lang = d.lang; - } - if (d.updated !== undefined) { - this.updated = d.updated; - } - if (d.currentItemCount !== undefined) { - this.currentItemCount = d.currentItemCount; - } - if (d.itemsPerPage !== undefined) { - this.itemsPerPage = d.itemsPerPage; - } - if (d.startIndex !== undefined) { - this.startIndex = d.startIndex; - } - if (d.totalItems !== undefined) { - this.totalItems = d.totalItems; - } - if (d.totalAvailableItems !== undefined) { - this.totalAvailableItems = d.totalAvailableItems; - } - if (d.pageIndex !== undefined) { - this.pageIndex = d.pageIndex; - } - if (d.totalPages !== undefined) { - this.totalPages = d.totalPages; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - item: this.#item, - items: this.#items, - editLink: this.#editLink, - selfLink: this.#selfLink, - kind: this.#kind, - fields: this.#fields, - etag: this.#etag, - cursor: this.#cursor, - id: this.#id, - lang: this.#lang, - updated: this.#updated, - currentItemCount: this.#currentItemCount, - itemsPerPage: this.#itemsPerPage, - startIndex: this.#startIndex, - totalItems: this.#totalItems, - totalAvailableItems: this.#totalAvailableItems, - pageIndex: this.#pageIndex, - totalPages: this.#totalPages, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - item: "item", - items: "items", - editLink: "editLink", - selfLink: "selfLink", - kind: "kind", - fields: "fields", - etag: "etag", - cursor: "cursor", - id: "id", - lang: "lang", - updated: "updated", - currentItemCount: "currentItemCount", - itemsPerPage: "itemsPerPage", - startIndex: "startIndex", - totalItems: "totalItems", - totalAvailableItems: "totalAvailableItems", - pageIndex: "pageIndex", - totalPages: "totalPages", - }; - } - /** - * Creates an instance of ResponseDto.Data, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.DataType) { - return new ResponseDto.Data(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Data, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep>, - ) { - return new ResponseDto.Data(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto.Data({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Data(this.toJSON()); - } - }; - /** - * The base class definition for error - **/ - static Error = class Error { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - #code: number = 0; - /** - * Numeric error code representing the failure. - * @returns {number} - **/ - get code() { - return this.#code; - } - /** - * Numeric error code representing the failure. - * @type {number} - **/ - set code(value: number) { - const correctType = typeof value === "number"; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#code = parsedValue; - } - } - setCode(value: number) { - this.code = value; - return this; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - #message: string = ""; - /** - * Human-readable explanation of the error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - set message(value: string) { - this.#message = String(value); - } - setMessage(value: string) { - this.message = value; - return this; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - #messageTranslated: string = ""; - /** - * Localized/translated version of the error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - set messageTranslated(value: string) { - this.#messageTranslated = String(value); - } - setMessageTranslated(value: string) { - this.messageTranslated = value; - return this; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - #errors: InstanceType[] = []; - /** - * Detailed list of error objects. - * @returns {ResponseDto.Error.Errors} - **/ - get errors() { - return this.#errors; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - set errors(value: InstanceType[]) { - // For arrays, you only can pass arrays to the object - if (!Array.isArray(value)) { - return; - } - if (value.length > 0 && value[0] instanceof ResponseDto.Error.Errors) { - this.#errors = value; - } else { - this.#errors = value.map((item) => new ResponseDto.Error.Errors(item)); - } - } - setErrors(value: InstanceType[]) { - this.errors = value; - return this; - } - /** - * The base class definition for errors - **/ - static Errors = class Errors { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - #domain?: string | null = undefined; - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @returns {string} - **/ - get domain() { - return this.#domain; - } - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - set domain(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#domain = correctType ? value : String(value); - } - setDomain(value: string | null | undefined) { - this.domain = value; - return this; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - #reason?: string | null = undefined; - /** - * Reason identifier for the error. - * @returns {string} - **/ - get reason() { - return this.#reason; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - set reason(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#reason = correctType ? value : String(value); - } - setReason(value: string | null | undefined) { - this.reason = value; - return this; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - #message?: string | null = undefined; - /** - * Human-readable explanation of the sub-error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - set message(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#message = correctType ? value : String(value); - } - setMessage(value: string | null | undefined) { - this.message = value; - return this; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - #messageTranslated?: string | null = undefined; - /** - * Localized/translated version of the sub-error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - set messageTranslated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#messageTranslated = correctType ? value : String(value); - } - setMessageTranslated(value: string | null | undefined) { - this.messageTranslated = value; - return this; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - #location?: string | null = undefined; - /** - * Field or parameter in which the error occurred. - * @returns {string} - **/ - get location() { - return this.#location; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - set location(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#location = correctType ? value : String(value); - } - setLocation(value: string | null | undefined) { - this.location = value; - return this; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - #locationType?: string | null = undefined; - /** - * Type of location (e.g., parameter, header). - * @returns {string} - **/ - get locationType() { - return this.#locationType; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - set locationType(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#locationType = correctType ? value : String(value); - } - setLocationType(value: string | null | undefined) { - this.locationType = value; - return this; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - #extendedHelp?: string | null = undefined; - /** - * URL linking to additional documentation about the error. - * @returns {string} - **/ - get extendedHelp() { - return this.#extendedHelp; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - set extendedHelp(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#extendedHelp = correctType ? value : String(value); - } - setExtendedHelp(value: string | null | undefined) { - this.extendedHelp = value; - return this; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - #sendReport?: string | null = undefined; - /** - * URL to submit a report for this error. - * @returns {string} - **/ - get sendReport() { - return this.#sendReport; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - set sendReport(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#sendReport = correctType ? value : String(value); - } - setSendReport(value: string | null | undefined) { - this.sendReport = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.domain !== undefined) { - this.domain = d.domain; - } - if (d.reason !== undefined) { - this.reason = d.reason; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.location !== undefined) { - this.location = d.location; - } - if (d.locationType !== undefined) { - this.locationType = d.locationType; - } - if (d.extendedHelp !== undefined) { - this.extendedHelp = d.extendedHelp; - } - if (d.sendReport !== undefined) { - this.sendReport = d.sendReport; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - domain: this.#domain, - reason: this.#reason, - message: this.#message, - messageTranslated: this.#messageTranslated, - location: this.#location, - locationType: this.#locationType, - extendedHelp: this.#extendedHelp, - sendReport: this.#sendReport, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - domain: "domain", - reason: "reason", - message: "message", - messageTranslated: "messageTranslated", - location: "location", - locationType: "locationType", - extendedHelp: "extendedHelp", - sendReport: "sendReport", - }; - } - /** - * Creates an instance of ResponseDto.Error.Errors, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType.ErrorsType) { - return new ResponseDto.Error.Errors(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error.Errors, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep, - ) { - return new ResponseDto.Error.Errors(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error.Errors({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error.Errors(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.code !== undefined) { - this.code = d.code; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.errors !== undefined) { - this.errors = d.errors; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - code: this.#code, - message: this.#message, - messageTranslated: this.#messageTranslated, - errors: this.#errors, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - code: "code", - message: "message", - messageTranslated: "messageTranslated", - errors$: "errors", - get errors() { - return withPrefix( - "error.errors[:i]", - ResponseDto.Error.Errors.Fields, - ); - }, - }; - } - /** - * Creates an instance of ResponseDto.Error, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType) { - return new ResponseDto.Error(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep) { - return new ResponseDto.Error(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - this.#lateInitFields(); - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.apiVersion !== undefined) { - this.apiVersion = d.apiVersion; - } - if (d.context !== undefined) { - this.context = d.context; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.method !== undefined) { - this.method = d.method; - } - if (d.params !== undefined) { - this.params = d.params; - } - if (d.data !== undefined) { - this.data = d.data; - } - if (d.error !== undefined) { - this.error = d.error; - } - this.#lateInitFields(data); - } - /** - * These are the class instances, which need to be initialised, regardless of the constructor incoming data - **/ - #lateInitFields(data = {}) { - const d = data as Partial>; - if (!(d.data instanceof ResponseDto.Data)) { - this.data = new ResponseDto.Data(d.data || {}); - } - if (!(d.error instanceof ResponseDto.Error)) { - this.error = new ResponseDto.Error(d.error || {}); - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - apiVersion: this.#apiVersion, - context: this.#context, - id: this.#id, - method: this.#method, - params: this.#params, - data: this.#data, - error: this.#error, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - apiVersion: "apiVersion", - context: "context", - id: "id", - method: "method", - params: "params", - data$: "data", - get data() { - return withPrefix("data", ResponseDto.Data.Fields); - }, - error$: "error", - get error() { - return withPrefix("error", ResponseDto.Error.Fields); - }, - }; - } - /** - * Creates an instance of ResponseDto, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType) { - return new ResponseDto(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep>) { - return new ResponseDto(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto(this.toJSON()); - } -} -export abstract class ResponseDtoFactory { - abstract create(data: unknown): ResponseDto; -} -type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; -/** - * The base type definition for responseDto - **/ -export type ResponseDtoType = { - /** - * Version of the API used for this response. - * @type {string} - **/ - apiVersion?: string; - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - context?: string; - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - id?: string; - /** - * Name of the API method invoked. - * @type {string} - **/ - method?: string; - /** - * Parameters sent with the request. - * @type {any} - **/ - params: any; - /** - * Main data payload of the response. - * @type {ResponseDtoType.DataType} - **/ - data: ResponseDtoType.DataType; - /** - * Error details, if the request failed. - * @type {ResponseDtoType.ErrorType} - **/ - error: ResponseDtoType.ErrorType; -}; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ResponseDtoType { - /** - * The base type definition for dataType - **/ - export type DataType = { - /** - * Single item returned by the API. - * @type {any} - **/ - item2: T; - /** - * List of items returned by the API. - * @type {any} - **/ - items: any; - /** - * Link to edit this resource. - * @type {string} - **/ - editLink?: string; - /** - * Link to retrieve this resource. - * @type {string} - **/ - selfLink?: string; - /** - * Resource type (kind) identifier. - * @type {string} - **/ - kind?: string; - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - fields?: string; - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - etag?: string; - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - cursor?: string; - /** - * Unique identifier of the resource. - * @type {string} - **/ - id?: string; - /** - * Language code of the response data. - * @type {string} - **/ - lang?: string; - /** - * Last modification time of the resource. - * @type {string} - **/ - updated?: string; - /** - * Number of items in the current response page. - * @type {number} - **/ - currentItemCount?: number; - /** - * Maximum number of items per page. - * @type {number} - **/ - itemsPerPage?: number; - /** - * Index of the first item in the current page. - * @type {number} - **/ - startIndex?: number; - /** - * Total number of items available. - * @type {number} - **/ - totalItems?: number; - /** - * Number of items available for this user/query. - * @type {number} - **/ - totalAvailableItems?: number; - /** - * Current page index in the pagination. - * @type {number} - **/ - pageIndex?: number; - /** - * Total number of pages in the pagination. - * @type {number} - **/ - totalPages?: number; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace DataType {} - /** - * The base type definition for errorType - **/ - export type ErrorType = { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - code: number; - /** - * Human-readable explanation of the error. - * @type {string} - **/ - message: string; - /** - * Localized/translated version of the error message. - * @type {string} - **/ - messageTranslated: string; - /** - * Detailed list of error objects. - * @type {ResponseDtoType.ErrorType.ErrorsType[]} - **/ - errors: ResponseDtoType.ErrorType.ErrorsType[]; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorType { - /** - * The base type definition for errorsType - **/ - export type ErrorsType = { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - domain?: string; - /** - * Reason identifier for the error. - * @type {string} - **/ - reason?: string; - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - message?: string; - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - messageTranslated?: string; - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - location?: string; - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - locationType?: string; - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - extendedHelp?: string; - /** - * URL to submit a report for this error. - * @type {string} - **/ - sendReport?: string; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorsType {} - } -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json deleted file mode 100644 index 7a3dc447..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "sdk", - "version": "1.0.0", - "description": "Auto-generated package.json", - "main": "index.js", - "scripts": { - "build": "echo 'build script here'", - "test": "echo 'test script here'" - }, - "dependencies": { - "@types/qs": "^6.14.0", - "qs": "^6.14.0" - } -} \ No newline at end of file diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml deleted file mode 100644 index 0dcb101c..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: googleEnvelop -description: - Generating envelop API responses using Emi itself. - Emi codegen is so strong that can generate deep classes in javascript which could be used - in itself and in this example we are doing it. - - All responses can be wrapped in google json styleguide, which gives extream consistency. - -dtos: - - name: response - fields: - - name: apiVersion - type: string? - description: Version of the API used for this response. - - name: context - type: string? - description: Context string provided by the client or system for request tracking. - - name: id - type: string? - description: Unique identifier assigned to the request/response. - - name: method - type: string? - description: Name of the API method invoked. - - name: params - type: any - description: Parameters sent with the request. - - name: data - type: object - description: Main data payload of the response. - fields: - - name: item - type: any - description: Single item returned by the API. - - name: items - type: any - description: List of items returned by the API. - - name: editLink - type: string? - description: Link to edit this resource. - - name: selfLink - type: string? - description: Link to retrieve this resource. - - name: kind - type: string? - description: Resource type (kind) identifier. - - name: fields - type: string? - description: Selector specifying which fields are included in a partial response. - - name: etag - type: string? - description: ETag of the resource, used for caching/version control. - - name: cursor - type: string? - description: Cursor for paginated data fetching. - - name: id - type: string? - description: Unique identifier of the resource. - - name: lang - type: string? - description: Language code of the response data. - - name: updated - type: string? - description: Last modification time of the resource. - - name: currentItemCount - type: int? - description: Number of items in the current response page. - - name: itemsPerPage - type: int? - description: Maximum number of items per page. - - name: startIndex - type: int? - description: Index of the first item in the current page. - - name: totalItems - type: int? - description: Total number of items available. - - name: totalAvailableItems - type: int? - description: Number of items available for this user/query. - - name: pageIndex - type: int? - description: Current page index in the pagination. - - name: totalPages - type: int? - description: Total number of pages in the pagination. - - name: error - type: object - description: Error details, if the request failed. - fields: - - name: code - type: int - description: Numeric error code representing the failure. - - name: message - type: string - description: Human-readable explanation of the error. - - name: messageTranslated - type: string - description: Localized/translated version of the error message. - - name: errors - type: array - description: Detailed list of error objects. - fields: - - name: domain - type: string? - description: Logical grouping of the error (e.g., global, usageLimits). - - name: reason - type: string? - description: Reason identifier for the error. - - name: message - type: string? - description: Human-readable explanation of the sub-error. - - name: messageTranslated - type: string? - description: Localized/translated version of the sub-error message. - - name: location - type: string? - description: Field or parameter in which the error occurred. - - name: locationType - type: string? - description: Type of location (e.g., parameter, header). - - name: extendedHelp - type: string? - description: URL linking to additional documentation about the error. - - name: sendReport - type: string? - description: URL to submit a report for this error. diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts deleted file mode 100644 index 2fc2601b..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/google-json-style-guide/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; -import { ResponseDto } from "./generated/ResponseDto"; -// Use this class to generate a GResponse. -export class GResponse extends ResponseDto implements EnvelopeClass { - creator?: CreatorSignature | null; - constructor(data?: unknown) { - super(data); - } - setCreator(fn: CreatorSignature) { - this.creator = fn; - return this; - } - /** - * GResponse can have data.item or data.items - * We create that based on incoming data tpye, so there is no need for 2 different - * classes, one for array and other for singular - * @param data - * @returns - */ - inject(body: any): this { - this.applyFromObject(body); - if ((body as any)?.data) { - if (!this.data) { - this.setData({} as any); - } - if ( - Array.isArray(body?.data.items) && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItems( - body?.data?.items?.map((item: unknown) => this.creator?.(item)), - ); - } else if ( - typeof body?.data?.item === "object" && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItem(this.creator(body?.data?.item)); - } else { - this.data?.setItem(body?.data?.item); - } - } - return this; - } -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/index.ts b/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/index.ts deleted file mode 100644 index 63d3ef26..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-management/sdk/envelopes/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./google-json-style-guide/index"; -export * from "./flat-array/FlatArray"; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/GetOfferTranslationsAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/GetOfferTranslationsAction.ts index 90e8b946..7bfb6fa3 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/GetOfferTranslationsAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-translations/GetOfferTranslationsAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -181,9 +174,9 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations} **/ - #translations: InstanceType< - typeof GetOfferTranslationsActionRes.Translations - >[] = []; + #translations: MArray< + InstanceType + > = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations} @@ -196,24 +189,47 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations} **/ set translations( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetOfferTranslationsActionRes.Translations + ) { + this.#translations = MArray.of(value); + } else { + this.#translations = MArray.of( + value.map( + (item) => new GetOfferTranslationsActionRes.Translations(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetOfferTranslationsActionRes.Translations - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#translations = value; - } else { - this.#translations = value.map( - (item) => new GetOfferTranslationsActionRes.Translations(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#translations = mcastValue as any; + return; } + console.warn( + "Cannot assing value to translations, because it needs MArray instance or an Array.", + ); } setTranslations( - value: InstanceType[], + value: + | MArray> + | InstanceType[], ) { this.translations = value; return this; @@ -601,9 +617,11 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections} **/ - #sections: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections - >[] = []; + #sections: MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections + > + > = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections} @@ -616,33 +634,64 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections} **/ set sections( - value: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections - >[], + value: + | MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections + > + > + | InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferTranslationsActionRes.Translations.Description + .Translation.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferTranslationsActionRes.Translations.Description.Translation - .Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue as any; + return; } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections( - value: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections - >[], + value: + | MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections + > + > + | InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections + >[], ) { this.sections = value; return this; @@ -655,9 +704,11 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items} **/ - #items: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items - >[] = []; + #items: MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items + > + > = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items} @@ -670,33 +721,64 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items} **/ set items( - value: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items + > + > + | InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferTranslationsActionRes.Translations.Description + .Translation.Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferTranslationsActionRes.Translations.Description - .Translation.Sections.Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items + > + > + | InstanceType< + typeof GetOfferTranslationsActionRes.Translations.Description.Translation.Sections.Items + >[], ) { this.items = value; return this; @@ -1176,9 +1258,11 @@ export class GetOfferTranslationsActionRes { * * @type {GetOfferTranslationsActionRes.Translations.SafetyInformation.Products} **/ - #products: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products - >[] = []; + #products: MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products + > + > = MArray.of([]); /** * * @returns {GetOfferTranslationsActionRes.Translations.SafetyInformation.Products} @@ -1191,33 +1275,64 @@ export class GetOfferTranslationsActionRes { * @type {GetOfferTranslationsActionRes.Translations.SafetyInformation.Products} **/ set products( - value: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products - >[], + value: + | MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products + > + > + | InstanceType< + typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetOfferTranslationsActionRes.Translations.SafetyInformation + .Products + ) { + this.#products = MArray.of(value); + } else { + this.#products = MArray.of( + value.map( + (item) => + new GetOfferTranslationsActionRes.Translations.SafetyInformation.Products( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetOfferTranslationsActionRes.Translations.SafetyInformation - .Products - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#products = value; - } else { - this.#products = value.map( - (item) => - new GetOfferTranslationsActionRes.Translations.SafetyInformation.Products( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#products = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to products, because it needs MArray instance or an Array.", + ); } setProducts( - value: InstanceType< - typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products - >[], + value: + | MArray< + InstanceType< + typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products + > + > + | InstanceType< + typeof GetOfferTranslationsActionRes.Translations.SafetyInformation.Products + >[], ) { this.products = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/UpdateOfferTranslationAction.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/UpdateOfferTranslationAction.ts index 0bc52b99..32444bf8 100644 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/UpdateOfferTranslationAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/offer-translations/UpdateOfferTranslationAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -298,9 +291,11 @@ export class UpdateOfferTranslationActionReq { * * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections} **/ - #sections: InstanceType< - typeof UpdateOfferTranslationActionReq.Description.Translation.Sections - >[] = []; + #sections: MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections + > + > = MArray.of([]); /** * * @returns {UpdateOfferTranslationActionReq.Description.Translation.Sections} @@ -313,32 +308,63 @@ export class UpdateOfferTranslationActionReq { * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections} **/ set sections( - value: InstanceType< - typeof UpdateOfferTranslationActionReq.Description.Translation.Sections - >[], + value: + | MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections + > + > + | InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + UpdateOfferTranslationActionReq.Description.Translation.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new UpdateOfferTranslationActionReq.Description.Translation.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - UpdateOfferTranslationActionReq.Description.Translation.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new UpdateOfferTranslationActionReq.Description.Translation.Sections( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue as any; + return; } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections( - value: InstanceType< - typeof UpdateOfferTranslationActionReq.Description.Translation.Sections - >[], + value: + | MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections + > + > + | InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections + >[], ) { this.sections = value; return this; @@ -351,9 +377,11 @@ export class UpdateOfferTranslationActionReq { * * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections.Items} **/ - #items: InstanceType< - typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items - >[] = []; + #items: MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items + > + > = MArray.of([]); /** * * @returns {UpdateOfferTranslationActionReq.Description.Translation.Sections.Items} @@ -366,33 +394,64 @@ export class UpdateOfferTranslationActionReq { * @type {UpdateOfferTranslationActionReq.Description.Translation.Sections.Items} **/ set items( - value: InstanceType< - typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items + > + > + | InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + UpdateOfferTranslationActionReq.Description.Translation.Sections + .Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new UpdateOfferTranslationActionReq.Description.Translation.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - UpdateOfferTranslationActionReq.Description.Translation.Sections - .Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new UpdateOfferTranslationActionReq.Description.Translation.Sections.Items( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items + > + > + | InstanceType< + typeof UpdateOfferTranslationActionReq.Description.Translation.Sections.Items + >[], ) { this.items = value; return this; @@ -972,9 +1031,11 @@ export class UpdateOfferTranslationActionReq { * * @type {UpdateOfferTranslationActionReq.SafetyInformation.Products} **/ - #products: InstanceType< - typeof UpdateOfferTranslationActionReq.SafetyInformation.Products - >[] = []; + #products: MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.SafetyInformation.Products + > + > = MArray.of([]); /** * * @returns {UpdateOfferTranslationActionReq.SafetyInformation.Products} @@ -987,32 +1048,63 @@ export class UpdateOfferTranslationActionReq { * @type {UpdateOfferTranslationActionReq.SafetyInformation.Products} **/ set products( - value: InstanceType< - typeof UpdateOfferTranslationActionReq.SafetyInformation.Products - >[], + value: + | MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.SafetyInformation.Products + > + > + | InstanceType< + typeof UpdateOfferTranslationActionReq.SafetyInformation.Products + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + UpdateOfferTranslationActionReq.SafetyInformation.Products + ) { + this.#products = MArray.of(value); + } else { + this.#products = MArray.of( + value.map( + (item) => + new UpdateOfferTranslationActionReq.SafetyInformation.Products( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - UpdateOfferTranslationActionReq.SafetyInformation.Products - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#products = value; - } else { - this.#products = value.map( - (item) => - new UpdateOfferTranslationActionReq.SafetyInformation.Products( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#products = mcastValue as any; + return; } + console.warn( + "Cannot assing value to products, because it needs MArray instance or an Array.", + ); } setProducts( - value: InstanceType< - typeof UpdateOfferTranslationActionReq.SafetyInformation.Products - >[], + value: + | MArray< + InstanceType< + typeof UpdateOfferTranslationActionReq.SafetyInformation.Products + > + > + | InstanceType< + typeof UpdateOfferTranslationActionReq.SafetyInformation.Products + >[], ) { this.products = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/buildUrl.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/buildUrl.ts deleted file mode 100644 index cf08f1cc..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/buildUrl.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Handy tool to create a final callable url, from query string, query params, - * and the actual url. - * @param template - * @param params - * @param qs - * @returns - */ -export function buildUrl( - url: string, - params?: Record, - qs?: URLSearchParams -) { - // Replace :placeholders - if (params) { - Object.entries(params as Record).forEach(([key, value]) => { - url = url.replace( - new RegExp(`:${key}`, "g"), - encodeURIComponent(String(value)) - ); - }); - } - - if (qs && qs instanceof URLSearchParams) { - url += `?${qs.toString()}`; - } else if (qs && Object.keys(qs).length) { - const query = new URLSearchParams( - Object.entries(qs).map(([k, v]) => [k, String(v)]) - ).toString(); - url += `?${query}`; - } - - return url; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/fetchx.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/fetchx.ts deleted file mode 100644 index 774f16b0..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/fetchx.ts +++ /dev/null @@ -1,196 +0,0 @@ -export type TypedRequestInit = Omit< - RequestInit, - "body" | "headers" -> & { - body?: TBody; - headers?: THeaders; -}; -export class TypedResponse extends Response { - override json(): Promise { - return super.json(); - } - result: - | T - | undefined - | ReadableStream> - | null - | string; -} -export async function fetchx< - TResponse = unknown, - TBody = unknown, - THeaders = unknown, ->( - input: RequestInfo | URL, - init?: TypedRequestInit, - ctx?: FetchxContext | null, -): Promise> { - let url = input.toString(); - let reqInit: TypedRequestInit = init || {}; - let res: TypedResponse; - let fetchFn = fetch; - - if (ctx) { - [url, reqInit] = await ctx.apply(url, reqInit); - - if (ctx.fetchOverrideFn) { - fetchFn = ctx.fetchOverrideFn; - } - } - - res = (await fetchFn( - url, - reqInit as RequestInit, - )) as TypedResponse; - - if (ctx) { - res = await ctx.handle(res); - } - return res; -} -type DtoFactory = { new (data: any): T } | ((data: any) => T); -function isConstructor(fn: DtoFactory): fn is { new (data: any): T } { - return ( - typeof fn === "function" && fn.prototype && fn.prototype.constructor === fn - ); -} -export async function handleFetchResponse( - res: TypedResponse, - dto?: DtoFactory, - onMessage?: (msg: any) => void, - signal?: AbortSignal | null, -): Promise<{ done: Promise; response: TypedResponse }> { - const ct = res.headers.get("content-type") || ""; - const cd = res.headers.get("content-disposition") || ""; - if (ct.includes("text/event-stream")) { - return SSEFetch(res, onMessage, signal); - } - if ( - cd.includes("attachment") || - (!ct.includes("json") && !ct.startsWith("text/")) - ) { - (res as any).result = res.body; - } else if (ct.includes("application/json")) { - const json = await res.json(); - if (dto) { - if (isConstructor(dto)) { - (res as any).result = new dto(json); // ✅ class constructor - } else { - (res as any).result = dto(json); // ✅ factory function - } - } else { - (res as any).result = json; - } - } else { - (res as any).result = await res.text(); - } - return { done: Promise.resolve(), response: res as any }; -} -export const SSEFetch = ( - res: TypedResponse, - onMessage?: (ev: MessageEvent) => void, - signal?: AbortSignal | null, -): { response: TypedResponse; done: Promise } => { - if (!res.body) throw new Error("SSE requires readable body"); - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - const done = new Promise((resolve, reject) => { - function readChunk() { - reader - .read() - .then(({ done: finished, value }) => { - if (signal?.aborted) { - reader.cancel(); - return resolve(); // resolve on abort - } - if (finished) return resolve(); // normal end - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split("\n\n"); - buffer = parts.pop() || ""; - for (const part of parts) { - let data = ""; - let event = "message"; - part.split("\n").forEach((line) => { - if (line.startsWith("data:")) data += line.slice(5).trim(); - else if (line.startsWith("event:")) event = line.slice(6).trim(); - }); - if (data) { - if (data === "[DONE]") return resolve(); - onMessage?.(new MessageEvent(event, { data })); - } - } - readChunk(); - }) - .catch((err) => { - if (err.name === "AbortError") resolve(); - else reject(err); - }); - } - readChunk(); - }); - return { response: res, done }; -}; -export class FetchxContext { - constructor( - public baseUrl: string = "", - public defaultHeaders: Record = {}, - public requestInterceptor?: ( - url: string, - init: TypedRequestInit, - ) => - | Promise<[string, TypedRequestInit]> - | [string, TypedRequestInit], - public responseInterceptor?: ( - res: TypedResponse, - ) => Promise>, - /** - * Overrides the browser fetch function, for different purposes. It would recieve the same first 2 arguments as fetch, - * as well as third one of fetchx context. If you pass the fetch itself to override, it should have no effect. - */ - public fetchOverrideFn?: ( - input: RequestInfo | URL, - init?: TypedRequestInit, - ) => Promise, - ) {} - async apply( - url: string, - init: TypedRequestInit, - ): Promise<[string, TypedRequestInit]> { - // prefix baseUrl - if (!/^https?:\/\//.test(url)) { - url = this.baseUrl + url; - } - // merge default headers - (init.headers as unknown) = { - ...this.defaultHeaders, - ...((init.headers as object) || {}), - }; - // call request interceptor if present - if (this.requestInterceptor) { - return this.requestInterceptor(url, init); - } - return [url, init]; - } - async handle(res: TypedResponse): Promise> { - if (this.responseInterceptor) { - return this.responseInterceptor(res); - } - return res; - } - clone(overrides?: Partial): FetchxContext { - return new FetchxContext( - overrides?.baseUrl ?? this.baseUrl, - { ...this.defaultHeaders, ...(overrides?.defaultHeaders || {}) }, - overrides?.requestInterceptor ?? this.requestInterceptor, - overrides?.responseInterceptor ?? this.responseInterceptor, - ); - } -} -export type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; \ No newline at end of file diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/operators.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/operators.ts deleted file mode 100644 index 728da07e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/operators.ts +++ /dev/null @@ -1,173 +0,0 @@ -export class MOne { - private operation: string | null = null; - private selector: S | undefined; - - private content: T | undefined = undefined; - - isNull(): boolean { - return this.content === null; - } - - isSelector(): boolean { - return this.selector !== undefined && this.operation !== null; - } - - get(): T { - return this.content!; - } - - static of(value: T) { - const one = new MOne(); - one.content = value; - - return one; - } - - static select(selector: any) { - const one = new MOne(); - one.selector = selector; - one.operation = "replace"; - - return one; - } - - toJSON() { - // When its explicit replace, it means that we need to pass a selector, so reader will - // be able to replace it via internal mechanism - if (this.operation === "replace") { - return { - __operation: this.operation, - selector: this.selector, - }; - } - - return this.content; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, maybe just giving back one is enough. -export class MOneNullable extends MOne {} - -// Array describes how an incoming list should be applied to an existing one, -// mirroring emigo.Array on the Go side. It lets a PATCH-style payload say -// "replace the whole set" versus "append to the existing set". -// -// On the wire a "replace" is implicit (a bare array), while an "append" is -// tagged with __operation so the reader keeps the existing rows. This keeps -// the payload identical to the Go client/backend generators. -export class MArray { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "replace"; - - return arr; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "append"; - - return arr; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Array is enough. -export class MArrayNullable extends Array {} - -// Collection mirrors emigo.Collection on the Go side. Structurally it is the -// same as Array — a list carrying a "replace"/"append" operation — but it is a -// distinct field type: a collection holds a list of a target entity, whereas an -// array holds a list of an inline DTO. -export class MCollection { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "replace"; - - return collection; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "append"; - - return collection; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Collection is enough. -export class CollectionNullable extends MCollection {} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/withPrefix.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts deleted file mode 100644 index 850d7626..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/common/EnvelopeClass.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * To declare a new envelope class, you must follow these rules: - * 1. The constructor must accept any object, which will contain the parsed JSON message - * from a response. - * 2. Envelope classes must provide a function to update the payload. Since payloads are - * type-safe, they must be instantiated and passed to the envelope; the common constructor - * alone is not enough. - * 3. Enveope must have a way to provide the content back actually, in order to create a class out of them. - */ - -export type CreatorSignature = (item: unknown) => T; - -export interface EnvelopeClass { - setCreator(fn: CreatorSignature): this; - inject(data: unknown): this; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts deleted file mode 100644 index 455cdd2e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/flat-array/FlatArray.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; - -// Some responses are returning a flat array, without any other information -// regarding the pagination, etc. They start [{},{}...] style. -// For those which might have a single project which is array but none-standard, -// Use CaptureArray instead. - -export class FlatArray implements EnvelopeClass { - public data: T[] = []; - creator?: CreatorSignature | null = null; - - inject(data: unknown) { - if (!Array.isArray(data)) { - throw new Error( - "FlatArray can only work on flat array items, such as [{},...], and doesn't accept any other type" - ); - } - - if (typeof this.creator !== "undefined") { - this.data = data.map((item) => - (this.creator as CreatorSignature)(item) - ); - } else { - this.data = data; - } - - return this; - } - - setCreator(creator: CreatorSignature) { - this.creator = creator; - - return this; - } - - // Implement thigs here, which would make the flat array to act as an array actually, how can it become - // class instance as an array? -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts deleted file mode 100644 index 0c078ce3..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts +++ /dev/null @@ -1,1715 +0,0 @@ -import { withPrefix } from "./sdk/common/withPrefix"; -/** - * The base class definition for responseDto - **/ -export class ResponseDto { - /** - * Version of the API used for this response. - * @type {string} - **/ - #apiVersion?: string | null = undefined; - /** - * Version of the API used for this response. - * @returns {string} - **/ - get apiVersion() { - return this.#apiVersion; - } - /** - * Version of the API used for this response. - * @type {string} - **/ - set apiVersion(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#apiVersion = correctType ? value : String(value); - } - setApiVersion(value: string | null | undefined) { - this.apiVersion = value; - return this; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - #context?: string | null = undefined; - /** - * Context string provided by the client or system for request tracking. - * @returns {string} - **/ - get context() { - return this.#context; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - set context(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#context = correctType ? value : String(value); - } - setContext(value: string | null | undefined) { - this.context = value; - return this; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier assigned to the request/response. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - #method?: string | null = undefined; - /** - * Name of the API method invoked. - * @returns {string} - **/ - get method() { - return this.#method; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - set method(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#method = correctType ? value : String(value); - } - setMethod(value: string | null | undefined) { - this.method = value; - return this; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - #params: any = null; - /** - * Parameters sent with the request. - * @returns {any} - **/ - get params() { - return this.#params; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - set params(value: any) { - this.#params = value; - } - setParams(value: any) { - this.params = value; - return this; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - #data!: InstanceType>; - /** - * Main data payload of the response. - * @returns {ResponseDto.Data} - **/ - get data() { - return this.#data; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - set data(value: InstanceType>) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Data) { - this.#data = value; - } else { - this.#data = new ResponseDto.Data(value); - } - } - setData(value: InstanceType>) { - this.data = value; - return this; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - #error!: InstanceType; - /** - * Error details, if the request failed. - * @returns {ResponseDto.Error} - **/ - get error() { - return this.#error; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - set error(value: InstanceType) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Error) { - this.#error = value; - } else { - this.#error = new ResponseDto.Error(value); - } - } - setError(value: InstanceType) { - this.error = value; - return this; - } - /** - * The base class definition for data - **/ - static Data = class Data { - /** - * Single item returned by the API. - * @type {any} - **/ - #item: T | null = null; - /** - * Single item returned by the API. - * @returns {T} - **/ - get item(): T | null { - return this.#item; - } - /** - * Single item returned by the API. - * @type {any} - **/ - set item(value: any) { - this.#item = value; - } - setItem(value: any) { - this.item = value; - return this; - } - /** - * List of items returned by the API. - * @type {any} - **/ - #items: T[] = []; - /** - * List of items returned by the API. - * @returns {T[]} - **/ - get items(): T[] { - return this.#items; - } - /** - * List of items returned by the API. - * @type {T[]} - **/ - set items(value: T[]) { - this.#items = value; - } - setItems(value: T[]) { - this.items = value; - return this; - } - /** - * Link to edit this resource. - * @type {string} - **/ - #editLink?: string | null = undefined; - /** - * Link to edit this resource. - * @returns {string} - **/ - get editLink() { - return this.#editLink; - } - /** - * Link to edit this resource. - * @type {string} - **/ - set editLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#editLink = correctType ? value : String(value); - } - setEditLink(value: string | null | undefined) { - this.editLink = value; - return this; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - #selfLink?: string | null = undefined; - /** - * Link to retrieve this resource. - * @returns {string} - **/ - get selfLink() { - return this.#selfLink; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - set selfLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#selfLink = correctType ? value : String(value); - } - setSelfLink(value: string | null | undefined) { - this.selfLink = value; - return this; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - #kind?: string | null = undefined; - /** - * Resource type (kind) identifier. - * @returns {string} - **/ - get kind() { - return this.#kind; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - set kind(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#kind = correctType ? value : String(value); - } - setKind(value: string | null | undefined) { - this.kind = value; - return this; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - #fields?: string | null = undefined; - /** - * Selector specifying which fields are included in a partial response. - * @returns {string} - **/ - get fields() { - return this.#fields; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - set fields(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#fields = correctType ? value : String(value); - } - setFields(value: string | null | undefined) { - this.fields = value; - return this; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - #etag?: string | null = undefined; - /** - * ETag of the resource, used for caching/version control. - * @returns {string} - **/ - get etag() { - return this.#etag; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - set etag(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#etag = correctType ? value : String(value); - } - setEtag(value: string | null | undefined) { - this.etag = value; - return this; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - #cursor?: string | null = undefined; - /** - * Cursor for paginated data fetching. - * @returns {string} - **/ - get cursor() { - return this.#cursor; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - set cursor(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#cursor = correctType ? value : String(value); - } - setCursor(value: string | null | undefined) { - this.cursor = value; - return this; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier of the resource. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Language code of the response data. - * @type {string} - **/ - #lang?: string | null = undefined; - /** - * Language code of the response data. - * @returns {string} - **/ - get lang() { - return this.#lang; - } - /** - * Language code of the response data. - * @type {string} - **/ - set lang(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#lang = correctType ? value : String(value); - } - setLang(value: string | null | undefined) { - this.lang = value; - return this; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - #updated?: string | null = undefined; - /** - * Last modification time of the resource. - * @returns {string} - **/ - get updated() { - return this.#updated; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - set updated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#updated = correctType ? value : String(value); - } - setUpdated(value: string | null | undefined) { - this.updated = value; - return this; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - #currentItemCount?: number | null = undefined; - /** - * Number of items in the current response page. - * @returns {number} - **/ - get currentItemCount() { - return this.#currentItemCount; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - set currentItemCount(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#currentItemCount = parsedValue; - } - } - setCurrentItemCount(value: number | null | undefined) { - this.currentItemCount = value; - return this; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - #itemsPerPage?: number | null = undefined; - /** - * Maximum number of items per page. - * @returns {number} - **/ - get itemsPerPage() { - return this.#itemsPerPage; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - set itemsPerPage(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#itemsPerPage = parsedValue; - } - } - setItemsPerPage(value: number | null | undefined) { - this.itemsPerPage = value; - return this; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - #startIndex?: number | null = undefined; - /** - * Index of the first item in the current page. - * @returns {number} - **/ - get startIndex() { - return this.#startIndex; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - set startIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#startIndex = parsedValue; - } - } - setStartIndex(value: number | null | undefined) { - this.startIndex = value; - return this; - } - /** - * Total number of items available. - * @type {number} - **/ - #totalItems?: number | null = undefined; - /** - * Total number of items available. - * @returns {number} - **/ - get totalItems() { - return this.#totalItems; - } - /** - * Total number of items available. - * @type {number} - **/ - set totalItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalItems = parsedValue; - } - } - setTotalItems(value: number | null | undefined) { - this.totalItems = value; - return this; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - #totalAvailableItems?: number | null = undefined; - /** - * Number of items available for this user/query. - * @returns {number} - **/ - get totalAvailableItems() { - return this.#totalAvailableItems; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - set totalAvailableItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalAvailableItems = parsedValue; - } - } - setTotalAvailableItems(value: number | null | undefined) { - this.totalAvailableItems = value; - return this; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - #pageIndex?: number | null = undefined; - /** - * Current page index in the pagination. - * @returns {number} - **/ - get pageIndex() { - return this.#pageIndex; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - set pageIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#pageIndex = parsedValue; - } - } - setPageIndex(value: number | null | undefined) { - this.pageIndex = value; - return this; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - #totalPages?: number | null = undefined; - /** - * Total number of pages in the pagination. - * @returns {number} - **/ - get totalPages() { - return this.#totalPages; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - set totalPages(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalPages = parsedValue; - } - } - setTotalPages(value: number | null | undefined) { - this.totalPages = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.item !== undefined) { - this.item = d.item; - } - if (d.items !== undefined) { - this.items = d.items; - } - if (d.editLink !== undefined) { - this.editLink = d.editLink; - } - if (d.selfLink !== undefined) { - this.selfLink = d.selfLink; - } - if (d.kind !== undefined) { - this.kind = d.kind; - } - if (d.fields !== undefined) { - this.fields = d.fields; - } - if (d.etag !== undefined) { - this.etag = d.etag; - } - if (d.cursor !== undefined) { - this.cursor = d.cursor; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.lang !== undefined) { - this.lang = d.lang; - } - if (d.updated !== undefined) { - this.updated = d.updated; - } - if (d.currentItemCount !== undefined) { - this.currentItemCount = d.currentItemCount; - } - if (d.itemsPerPage !== undefined) { - this.itemsPerPage = d.itemsPerPage; - } - if (d.startIndex !== undefined) { - this.startIndex = d.startIndex; - } - if (d.totalItems !== undefined) { - this.totalItems = d.totalItems; - } - if (d.totalAvailableItems !== undefined) { - this.totalAvailableItems = d.totalAvailableItems; - } - if (d.pageIndex !== undefined) { - this.pageIndex = d.pageIndex; - } - if (d.totalPages !== undefined) { - this.totalPages = d.totalPages; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - item: this.#item, - items: this.#items, - editLink: this.#editLink, - selfLink: this.#selfLink, - kind: this.#kind, - fields: this.#fields, - etag: this.#etag, - cursor: this.#cursor, - id: this.#id, - lang: this.#lang, - updated: this.#updated, - currentItemCount: this.#currentItemCount, - itemsPerPage: this.#itemsPerPage, - startIndex: this.#startIndex, - totalItems: this.#totalItems, - totalAvailableItems: this.#totalAvailableItems, - pageIndex: this.#pageIndex, - totalPages: this.#totalPages, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - item: "item", - items: "items", - editLink: "editLink", - selfLink: "selfLink", - kind: "kind", - fields: "fields", - etag: "etag", - cursor: "cursor", - id: "id", - lang: "lang", - updated: "updated", - currentItemCount: "currentItemCount", - itemsPerPage: "itemsPerPage", - startIndex: "startIndex", - totalItems: "totalItems", - totalAvailableItems: "totalAvailableItems", - pageIndex: "pageIndex", - totalPages: "totalPages", - }; - } - /** - * Creates an instance of ResponseDto.Data, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.DataType) { - return new ResponseDto.Data(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Data, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep>, - ) { - return new ResponseDto.Data(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto.Data({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Data(this.toJSON()); - } - }; - /** - * The base class definition for error - **/ - static Error = class Error { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - #code: number = 0; - /** - * Numeric error code representing the failure. - * @returns {number} - **/ - get code() { - return this.#code; - } - /** - * Numeric error code representing the failure. - * @type {number} - **/ - set code(value: number) { - const correctType = typeof value === "number"; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#code = parsedValue; - } - } - setCode(value: number) { - this.code = value; - return this; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - #message: string = ""; - /** - * Human-readable explanation of the error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - set message(value: string) { - this.#message = String(value); - } - setMessage(value: string) { - this.message = value; - return this; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - #messageTranslated: string = ""; - /** - * Localized/translated version of the error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - set messageTranslated(value: string) { - this.#messageTranslated = String(value); - } - setMessageTranslated(value: string) { - this.messageTranslated = value; - return this; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - #errors: InstanceType[] = []; - /** - * Detailed list of error objects. - * @returns {ResponseDto.Error.Errors} - **/ - get errors() { - return this.#errors; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - set errors(value: InstanceType[]) { - // For arrays, you only can pass arrays to the object - if (!Array.isArray(value)) { - return; - } - if (value.length > 0 && value[0] instanceof ResponseDto.Error.Errors) { - this.#errors = value; - } else { - this.#errors = value.map((item) => new ResponseDto.Error.Errors(item)); - } - } - setErrors(value: InstanceType[]) { - this.errors = value; - return this; - } - /** - * The base class definition for errors - **/ - static Errors = class Errors { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - #domain?: string | null = undefined; - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @returns {string} - **/ - get domain() { - return this.#domain; - } - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - set domain(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#domain = correctType ? value : String(value); - } - setDomain(value: string | null | undefined) { - this.domain = value; - return this; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - #reason?: string | null = undefined; - /** - * Reason identifier for the error. - * @returns {string} - **/ - get reason() { - return this.#reason; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - set reason(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#reason = correctType ? value : String(value); - } - setReason(value: string | null | undefined) { - this.reason = value; - return this; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - #message?: string | null = undefined; - /** - * Human-readable explanation of the sub-error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - set message(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#message = correctType ? value : String(value); - } - setMessage(value: string | null | undefined) { - this.message = value; - return this; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - #messageTranslated?: string | null = undefined; - /** - * Localized/translated version of the sub-error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - set messageTranslated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#messageTranslated = correctType ? value : String(value); - } - setMessageTranslated(value: string | null | undefined) { - this.messageTranslated = value; - return this; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - #location?: string | null = undefined; - /** - * Field or parameter in which the error occurred. - * @returns {string} - **/ - get location() { - return this.#location; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - set location(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#location = correctType ? value : String(value); - } - setLocation(value: string | null | undefined) { - this.location = value; - return this; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - #locationType?: string | null = undefined; - /** - * Type of location (e.g., parameter, header). - * @returns {string} - **/ - get locationType() { - return this.#locationType; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - set locationType(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#locationType = correctType ? value : String(value); - } - setLocationType(value: string | null | undefined) { - this.locationType = value; - return this; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - #extendedHelp?: string | null = undefined; - /** - * URL linking to additional documentation about the error. - * @returns {string} - **/ - get extendedHelp() { - return this.#extendedHelp; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - set extendedHelp(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#extendedHelp = correctType ? value : String(value); - } - setExtendedHelp(value: string | null | undefined) { - this.extendedHelp = value; - return this; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - #sendReport?: string | null = undefined; - /** - * URL to submit a report for this error. - * @returns {string} - **/ - get sendReport() { - return this.#sendReport; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - set sendReport(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#sendReport = correctType ? value : String(value); - } - setSendReport(value: string | null | undefined) { - this.sendReport = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.domain !== undefined) { - this.domain = d.domain; - } - if (d.reason !== undefined) { - this.reason = d.reason; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.location !== undefined) { - this.location = d.location; - } - if (d.locationType !== undefined) { - this.locationType = d.locationType; - } - if (d.extendedHelp !== undefined) { - this.extendedHelp = d.extendedHelp; - } - if (d.sendReport !== undefined) { - this.sendReport = d.sendReport; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - domain: this.#domain, - reason: this.#reason, - message: this.#message, - messageTranslated: this.#messageTranslated, - location: this.#location, - locationType: this.#locationType, - extendedHelp: this.#extendedHelp, - sendReport: this.#sendReport, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - domain: "domain", - reason: "reason", - message: "message", - messageTranslated: "messageTranslated", - location: "location", - locationType: "locationType", - extendedHelp: "extendedHelp", - sendReport: "sendReport", - }; - } - /** - * Creates an instance of ResponseDto.Error.Errors, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType.ErrorsType) { - return new ResponseDto.Error.Errors(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error.Errors, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep, - ) { - return new ResponseDto.Error.Errors(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error.Errors({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error.Errors(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.code !== undefined) { - this.code = d.code; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.errors !== undefined) { - this.errors = d.errors; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - code: this.#code, - message: this.#message, - messageTranslated: this.#messageTranslated, - errors: this.#errors, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - code: "code", - message: "message", - messageTranslated: "messageTranslated", - errors$: "errors", - get errors() { - return withPrefix( - "error.errors[:i]", - ResponseDto.Error.Errors.Fields, - ); - }, - }; - } - /** - * Creates an instance of ResponseDto.Error, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType) { - return new ResponseDto.Error(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep) { - return new ResponseDto.Error(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - this.#lateInitFields(); - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.apiVersion !== undefined) { - this.apiVersion = d.apiVersion; - } - if (d.context !== undefined) { - this.context = d.context; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.method !== undefined) { - this.method = d.method; - } - if (d.params !== undefined) { - this.params = d.params; - } - if (d.data !== undefined) { - this.data = d.data; - } - if (d.error !== undefined) { - this.error = d.error; - } - this.#lateInitFields(data); - } - /** - * These are the class instances, which need to be initialised, regardless of the constructor incoming data - **/ - #lateInitFields(data = {}) { - const d = data as Partial>; - if (!(d.data instanceof ResponseDto.Data)) { - this.data = new ResponseDto.Data(d.data || {}); - } - if (!(d.error instanceof ResponseDto.Error)) { - this.error = new ResponseDto.Error(d.error || {}); - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - apiVersion: this.#apiVersion, - context: this.#context, - id: this.#id, - method: this.#method, - params: this.#params, - data: this.#data, - error: this.#error, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - apiVersion: "apiVersion", - context: "context", - id: "id", - method: "method", - params: "params", - data$: "data", - get data() { - return withPrefix("data", ResponseDto.Data.Fields); - }, - error$: "error", - get error() { - return withPrefix("error", ResponseDto.Error.Fields); - }, - }; - } - /** - * Creates an instance of ResponseDto, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType) { - return new ResponseDto(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep>) { - return new ResponseDto(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto(this.toJSON()); - } -} -export abstract class ResponseDtoFactory { - abstract create(data: unknown): ResponseDto; -} -type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; -/** - * The base type definition for responseDto - **/ -export type ResponseDtoType = { - /** - * Version of the API used for this response. - * @type {string} - **/ - apiVersion?: string; - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - context?: string; - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - id?: string; - /** - * Name of the API method invoked. - * @type {string} - **/ - method?: string; - /** - * Parameters sent with the request. - * @type {any} - **/ - params: any; - /** - * Main data payload of the response. - * @type {ResponseDtoType.DataType} - **/ - data: ResponseDtoType.DataType; - /** - * Error details, if the request failed. - * @type {ResponseDtoType.ErrorType} - **/ - error: ResponseDtoType.ErrorType; -}; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ResponseDtoType { - /** - * The base type definition for dataType - **/ - export type DataType = { - /** - * Single item returned by the API. - * @type {any} - **/ - item2: T; - /** - * List of items returned by the API. - * @type {any} - **/ - items: any; - /** - * Link to edit this resource. - * @type {string} - **/ - editLink?: string; - /** - * Link to retrieve this resource. - * @type {string} - **/ - selfLink?: string; - /** - * Resource type (kind) identifier. - * @type {string} - **/ - kind?: string; - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - fields?: string; - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - etag?: string; - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - cursor?: string; - /** - * Unique identifier of the resource. - * @type {string} - **/ - id?: string; - /** - * Language code of the response data. - * @type {string} - **/ - lang?: string; - /** - * Last modification time of the resource. - * @type {string} - **/ - updated?: string; - /** - * Number of items in the current response page. - * @type {number} - **/ - currentItemCount?: number; - /** - * Maximum number of items per page. - * @type {number} - **/ - itemsPerPage?: number; - /** - * Index of the first item in the current page. - * @type {number} - **/ - startIndex?: number; - /** - * Total number of items available. - * @type {number} - **/ - totalItems?: number; - /** - * Number of items available for this user/query. - * @type {number} - **/ - totalAvailableItems?: number; - /** - * Current page index in the pagination. - * @type {number} - **/ - pageIndex?: number; - /** - * Total number of pages in the pagination. - * @type {number} - **/ - totalPages?: number; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace DataType {} - /** - * The base type definition for errorType - **/ - export type ErrorType = { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - code: number; - /** - * Human-readable explanation of the error. - * @type {string} - **/ - message: string; - /** - * Localized/translated version of the error message. - * @type {string} - **/ - messageTranslated: string; - /** - * Detailed list of error objects. - * @type {ResponseDtoType.ErrorType.ErrorsType[]} - **/ - errors: ResponseDtoType.ErrorType.ErrorsType[]; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorType { - /** - * The base type definition for errorsType - **/ - export type ErrorsType = { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - domain?: string; - /** - * Reason identifier for the error. - * @type {string} - **/ - reason?: string; - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - message?: string; - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - messageTranslated?: string; - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - location?: string; - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - locationType?: string; - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - extendedHelp?: string; - /** - * URL to submit a report for this error. - * @type {string} - **/ - sendReport?: string; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorsType {} - } -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json deleted file mode 100644 index 7a3dc447..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "sdk", - "version": "1.0.0", - "description": "Auto-generated package.json", - "main": "index.js", - "scripts": { - "build": "echo 'build script here'", - "test": "echo 'test script here'" - }, - "dependencies": { - "@types/qs": "^6.14.0", - "qs": "^6.14.0" - } -} \ No newline at end of file diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml deleted file mode 100644 index 0dcb101c..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: googleEnvelop -description: - Generating envelop API responses using Emi itself. - Emi codegen is so strong that can generate deep classes in javascript which could be used - in itself and in this example we are doing it. - - All responses can be wrapped in google json styleguide, which gives extream consistency. - -dtos: - - name: response - fields: - - name: apiVersion - type: string? - description: Version of the API used for this response. - - name: context - type: string? - description: Context string provided by the client or system for request tracking. - - name: id - type: string? - description: Unique identifier assigned to the request/response. - - name: method - type: string? - description: Name of the API method invoked. - - name: params - type: any - description: Parameters sent with the request. - - name: data - type: object - description: Main data payload of the response. - fields: - - name: item - type: any - description: Single item returned by the API. - - name: items - type: any - description: List of items returned by the API. - - name: editLink - type: string? - description: Link to edit this resource. - - name: selfLink - type: string? - description: Link to retrieve this resource. - - name: kind - type: string? - description: Resource type (kind) identifier. - - name: fields - type: string? - description: Selector specifying which fields are included in a partial response. - - name: etag - type: string? - description: ETag of the resource, used for caching/version control. - - name: cursor - type: string? - description: Cursor for paginated data fetching. - - name: id - type: string? - description: Unique identifier of the resource. - - name: lang - type: string? - description: Language code of the response data. - - name: updated - type: string? - description: Last modification time of the resource. - - name: currentItemCount - type: int? - description: Number of items in the current response page. - - name: itemsPerPage - type: int? - description: Maximum number of items per page. - - name: startIndex - type: int? - description: Index of the first item in the current page. - - name: totalItems - type: int? - description: Total number of items available. - - name: totalAvailableItems - type: int? - description: Number of items available for this user/query. - - name: pageIndex - type: int? - description: Current page index in the pagination. - - name: totalPages - type: int? - description: Total number of pages in the pagination. - - name: error - type: object - description: Error details, if the request failed. - fields: - - name: code - type: int - description: Numeric error code representing the failure. - - name: message - type: string - description: Human-readable explanation of the error. - - name: messageTranslated - type: string - description: Localized/translated version of the error message. - - name: errors - type: array - description: Detailed list of error objects. - fields: - - name: domain - type: string? - description: Logical grouping of the error (e.g., global, usageLimits). - - name: reason - type: string? - description: Reason identifier for the error. - - name: message - type: string? - description: Human-readable explanation of the sub-error. - - name: messageTranslated - type: string? - description: Localized/translated version of the sub-error message. - - name: location - type: string? - description: Field or parameter in which the error occurred. - - name: locationType - type: string? - description: Type of location (e.g., parameter, header). - - name: extendedHelp - type: string? - description: URL linking to additional documentation about the error. - - name: sendReport - type: string? - description: URL to submit a report for this error. diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts deleted file mode 100644 index 2fc2601b..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/google-json-style-guide/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; -import { ResponseDto } from "./generated/ResponseDto"; -// Use this class to generate a GResponse. -export class GResponse extends ResponseDto implements EnvelopeClass { - creator?: CreatorSignature | null; - constructor(data?: unknown) { - super(data); - } - setCreator(fn: CreatorSignature) { - this.creator = fn; - return this; - } - /** - * GResponse can have data.item or data.items - * We create that based on incoming data tpye, so there is no need for 2 different - * classes, one for array and other for singular - * @param data - * @returns - */ - inject(body: any): this { - this.applyFromObject(body); - if ((body as any)?.data) { - if (!this.data) { - this.setData({} as any); - } - if ( - Array.isArray(body?.data.items) && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItems( - body?.data?.items?.map((item: unknown) => this.creator?.(item)), - ); - } else if ( - typeof body?.data?.item === "object" && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItem(this.creator(body?.data?.item)); - } else { - this.data?.setItem(body?.data?.item); - } - } - return this; - } -} diff --git a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/index.ts b/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/index.ts deleted file mode 100644 index 63d3ef26..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/offer-translations/sdk/envelopes/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./google-json-style-guide/index"; -export * from "./flat-array/FlatArray"; diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.ts index e9cec34d..5f5f013c 100644 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetAllDataOfTheParticularProductOfferAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -1329,9 +1322,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet} **/ - #productSet: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet - >[] = []; + #productSet: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet} @@ -1344,30 +1339,63 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet} **/ set productSet( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet + ) { + this.#productSet = MArray.of(value); + } else { + this.#productSet = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#productSet = value; - } else { - this.#productSet = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#productSet = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to productSet, because it needs MArray instance or an Array.", + ); } setProductSet( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet + >[], ) { this.productSet = value; return this; @@ -1376,9 +1404,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Attachments} **/ - #attachments: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments - >[] = []; + #attachments: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Attachments} @@ -1391,30 +1421,63 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Attachments} **/ set attachments( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Attachments + ) { + this.#attachments = MArray.of(value); + } else { + this.#attachments = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Attachments( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Attachments - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#attachments = value; - } else { - this.#attachments = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Attachments(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#attachments = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to attachments, because it needs MArray instance or an Array.", + ); } setAttachments( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Attachments + >[], ) { this.attachments = value; return this; @@ -2470,9 +2533,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional} **/ - #additional: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional - >[] = []; + #additional: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional} @@ -2485,33 +2550,64 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional} **/ set additional( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Publication + .Marketplaces.Additional + ) { + this.#additional = MArray.of(value); + } else { + this.#additional = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Publication - .Marketplaces.Additional - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additional = value; - } else { - this.#additional = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additional = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to additional, because it needs MArray instance or an Array.", + ); } setAdditional( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Publication.Marketplaces.Additional + >[], ) { this.additional = value; return this; @@ -5358,9 +5454,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections} **/ - #sections: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections - >[] = []; + #sections: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections} @@ -5373,32 +5471,63 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections} **/ set sections( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Description.Sections + ) { + this.#sections = MArray.of(value); + } else { + this.#sections = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Description.Sections - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#sections = value; - } else { - this.#sections = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#sections = mcastValue as any; + return; } + console.warn( + "Cannot assing value to sections, because it needs MArray instance or an Array.", + ); } setSections( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections + >[], ) { this.sections = value; return this; @@ -5411,9 +5540,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items} **/ - #items: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items - >[] = []; + #items: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items} @@ -5426,33 +5557,64 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items} **/ set items( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Description + .Sections.Items + ) { + this.#items = MArray.of(value); + } else { + this.#items = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Description.Sections - .Items - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#items = value; - } else { - this.#items = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#items = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to items, because it needs MArray instance or an Array.", + ); } setItems( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Description.Sections.Items + >[], ) { this.items = value; return this; @@ -6047,9 +6209,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits} **/ - #deposits: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits - >[] = []; + #deposits: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits} @@ -6062,32 +6226,63 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits} **/ set deposits( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits + ) { + this.#deposits = MArray.of(value); + } else { + this.#deposits = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#deposits = value; - } else { - this.#deposits = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#deposits = mcastValue as any; + return; } + console.warn( + "Cannot assing value to deposits, because it needs MArray instance or an Array.", + ); } setDeposits( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Deposits + >[], ) { this.deposits = value; return this; @@ -6320,9 +6515,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters} **/ - #parameters: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters - >[] = []; + #parameters: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters} @@ -6335,33 +6532,64 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters} **/ set parameters( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product + .Parameters + ) { + this.#parameters = MArray.of(value); + } else { + this.#parameters = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product - .Parameters - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#parameters = value; - } else { - this.#parameters = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#parameters = mcastValue as any; + return; } + console.warn( + "Cannot assing value to parameters, because it needs MArray instance or an Array.", + ); } setParameters( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters + >[], ) { this.parameters = value; return this; @@ -6590,9 +6818,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values} **/ - #values: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values - >[] = []; + #values: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values} @@ -6605,33 +6835,64 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values} **/ set values( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet + .Product.Parameters.Values + ) { + this.#values = MArray.of(value); + } else { + this.#values = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product - .Parameters.Values - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#values = value; - } else { - this.#values = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#values = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to values, because it needs MArray instance or an Array.", + ); } setValues( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.Values + >[], ) { this.values = value; return this; @@ -6640,9 +6901,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds} **/ - #valuesIds: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds - >[] = []; + #valuesIds: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds} @@ -6655,33 +6918,64 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds} **/ set valuesIds( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.ProductSet + .Product.Parameters.ValuesIds + ) { + this.#valuesIds = MArray.of(value); + } else { + this.#valuesIds = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product - .Parameters.ValuesIds - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#valuesIds = value; - } else { - this.#valuesIds = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#valuesIds = mcastValue as any; + return; } + console.warn( + "Cannot assing value to valuesIds, because it needs MArray instance or an Array.", + ); } setValuesIds( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.ProductSet.Product.Parameters.ValuesIds + >[], ) { this.valuesIds = value; return this; @@ -8791,9 +9085,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors} **/ - #errors: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors - >[] = []; + #errors: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors} @@ -8806,32 +9102,63 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors} **/ set errors( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors + ) { + this.#errors = MArray.of(value); + } else { + this.#errors = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#errors = value; - } else { - this.#errors = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#errors = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to errors, because it needs MArray instance or an Array.", + ); } setErrors( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Errors + >[], ) { this.errors = value; return this; @@ -8840,9 +9167,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings} **/ - #warnings: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings - >[] = []; + #warnings: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings} @@ -8855,32 +9184,63 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings} **/ set warnings( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings + ) { + this.#warnings = MArray.of(value); + } else { + this.#warnings = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#warnings = value; - } else { - this.#warnings = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#warnings = mcastValue as any; + return; } + console.warn( + "Cannot assing value to warnings, because it needs MArray instance or an Array.", + ); } setWarnings( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.Validation.Warnings + >[], ) { this.warnings = value; return this; @@ -10192,9 +10552,11 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * * @type {GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates} **/ - #rates: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates - >[] = []; + #rates: MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates + > + > = MArray.of([]); /** * * @returns {GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates} @@ -10207,32 +10569,63 @@ export class GetAllDataOfTheParticularProductOfferActionRes { * @type {GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates} **/ set rates( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates + ) { + this.#rates = MArray.of(value); + } else { + this.#rates = MArray.of( + value.map( + (item) => + new GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#rates = value; - } else { - this.#rates = value.map( - (item) => - new GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#rates = mcastValue as any; + return; } + console.warn( + "Cannot assing value to rates, because it needs MArray instance or an Array.", + ); } setRates( - value: InstanceType< - typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates - >[], + value: + | MArray< + InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates + > + > + | InstanceType< + typeof GetAllDataOfTheParticularProductOfferActionRes.TaxSettings.Rates + >[], ) { this.rates = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.ts index bac1b428..4eb86489 100644 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetEventsAboutTheSellerSOffersAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -146,9 +139,9 @@ export class GetEventsAboutTheSellerSOffersActionRes { * List of events related to offer state changes * @type {GetEventsAboutTheSellerSOffersActionRes.OfferEvents} **/ - #offerEvents: InstanceType< - typeof GetEventsAboutTheSellerSOffersActionRes.OfferEvents - >[] = []; + #offerEvents: MArray< + InstanceType + > = MArray.of([]); /** * List of events related to offer state changes * @returns {GetEventsAboutTheSellerSOffersActionRes.OfferEvents} @@ -161,28 +154,60 @@ export class GetEventsAboutTheSellerSOffersActionRes { * @type {GetEventsAboutTheSellerSOffersActionRes.OfferEvents} **/ set offerEvents( - value: InstanceType< - typeof GetEventsAboutTheSellerSOffersActionRes.OfferEvents - >[], + value: + | MArray< + InstanceType< + typeof GetEventsAboutTheSellerSOffersActionRes.OfferEvents + > + > + | InstanceType< + typeof GetEventsAboutTheSellerSOffersActionRes.OfferEvents + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetEventsAboutTheSellerSOffersActionRes.OfferEvents + ) { + this.#offerEvents = MArray.of(value); + } else { + this.#offerEvents = MArray.of( + value.map( + (item) => + new GetEventsAboutTheSellerSOffersActionRes.OfferEvents(item), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetEventsAboutTheSellerSOffersActionRes.OfferEvents - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offerEvents = value; - } else { - this.#offerEvents = value.map( - (item) => new GetEventsAboutTheSellerSOffersActionRes.OfferEvents(item), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offerEvents = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to offerEvents, because it needs MArray instance or an Array.", + ); } setOfferEvents( - value: InstanceType< - typeof GetEventsAboutTheSellerSOffersActionRes.OfferEvents - >[], + value: + | MArray< + InstanceType< + typeof GetEventsAboutTheSellerSOffersActionRes.OfferEvents + > + > + | InstanceType< + typeof GetEventsAboutTheSellerSOffersActionRes.OfferEvents + >[], ) { this.offerEvents = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.ts index 48a9fead..087de37f 100644 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSelectedDataOfTheParticularProductOfferAction.ts @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSellersOffersAction.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSellersOffersAction.ts index 26a22eeb..4bca5b0d 100644 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSellersOffersAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSellersOffersAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -534,7 +527,8 @@ export class GetSellersOffersActionRes { * * @type {GetSellersOffersActionRes.Offers} **/ - #offers: InstanceType[] = []; + #offers: MArray> = + MArray.of([]); /** * * @returns {GetSellersOffersActionRes.Offers} @@ -546,22 +540,47 @@ export class GetSellersOffersActionRes { * * @type {GetSellersOffersActionRes.Offers} **/ - set offers(value: InstanceType[]) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + set offers( + value: + | MArray> + | InstanceType[], + ) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof GetSellersOffersActionRes.Offers + ) { + this.#offers = MArray.of(value); + } else { + this.#offers = MArray.of( + value.map((item) => new GetSellersOffersActionRes.Offers(item)), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof GetSellersOffersActionRes.Offers - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#offers = value; - } else { - this.#offers = value.map( - (item) => new GetSellersOffersActionRes.Offers(item), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#offers = mcastValue as any; + return; } + console.warn( + "Cannot assing value to offers, because it needs MArray instance or an Array.", + ); } - setOffers(value: InstanceType[]) { + setOffers( + value: + | MArray> + | InstanceType[], + ) { this.offers = value; return this; } @@ -3347,9 +3366,11 @@ export class GetSellersOffersActionRes { * * @type {GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional} **/ - #additional: InstanceType< - typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional - >[] = []; + #additional: MArray< + InstanceType< + typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional + > + > = MArray.of([]); /** * * @returns {GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional} @@ -3362,33 +3383,64 @@ export class GetSellersOffersActionRes { * @type {GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional} **/ set additional( - value: InstanceType< - typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional - >[], + value: + | MArray< + InstanceType< + typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional + > + > + | InstanceType< + typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSellersOffersActionRes.Offers.Publication.Marketplaces + .Additional + ) { + this.#additional = MArray.of(value); + } else { + this.#additional = MArray.of( + value.map( + (item) => + new GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSellersOffersActionRes.Offers.Publication.Marketplaces - .Additional - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#additional = value; - } else { - this.#additional = value.map( - (item) => - new GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#additional = mcastValue as any; + return; } + console.warn( + "Cannot assing value to additional, because it needs MArray instance or an Array.", + ); } setAdditional( - value: InstanceType< - typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional - >[], + value: + | MArray< + InstanceType< + typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional + > + > + | InstanceType< + typeof GetSellersOffersActionRes.Offers.Publication.Marketplaces.Additional + >[], ) { this.additional = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.ts index 304c2487..781a466d 100644 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.ts +++ b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/GetSmartClassificationReportOfTheParticularOfferAction.ts @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators"; +import { MArray } from "./sdk/common/operators"; import { buildUrl } from "./sdk/common/buildUrl"; import { fetchx, @@ -269,9 +262,11 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * List of smart delivery method identifiers * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods} **/ - #smartDeliveryMethods: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods - >[] = []; + #smartDeliveryMethods: MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods + > + > = MArray.of([]); /** * List of smart delivery method identifiers * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods} @@ -284,32 +279,63 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods} **/ set smartDeliveryMethods( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods + ) { + this.#smartDeliveryMethods = MArray.of(value); + } else { + this.#smartDeliveryMethods = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#smartDeliveryMethods = value; - } else { - this.#smartDeliveryMethods = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#smartDeliveryMethods = mcastValue as any; + return; } + console.warn( + "Cannot assing value to smartDeliveryMethods, because it needs MArray instance or an Array.", + ); } setSmartDeliveryMethods( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.SmartDeliveryMethods + >[], ) { this.smartDeliveryMethods = value; return this; @@ -318,9 +344,11 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * List of classification conditions with delivery method checks * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions} **/ - #conditions: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - >[] = []; + #conditions: MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + > + > = MArray.of([]); /** * List of classification conditions with delivery method checks * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions} @@ -333,32 +361,63 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions} **/ set conditions( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + ) { + this.#conditions = MArray.of(value); + } else { + this.#conditions = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#conditions = value; - } else { - this.#conditions = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#conditions = mcastValue as any; + return; } + console.warn( + "Cannot assing value to conditions, because it needs MArray instance or an Array.", + ); } setConditions( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + >[], ) { this.conditions = value; return this; @@ -741,9 +800,11 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * Delivery methods that passed validation for this condition * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods} **/ - #passedDeliveryMethods: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods - >[] = []; + #passedDeliveryMethods: MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods + > + > = MArray.of([]); /** * Delivery methods that passed validation for this condition * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods} @@ -756,33 +817,64 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods} **/ set passedDeliveryMethods( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + .PassedDeliveryMethods + ) { + this.#passedDeliveryMethods = MArray.of(value); + } else { + this.#passedDeliveryMethods = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - .PassedDeliveryMethods - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#passedDeliveryMethods = value; - } else { - this.#passedDeliveryMethods = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods( - item, - ), - ); + return; } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#passedDeliveryMethods = mcastValue as any; + return; + } + console.warn( + "Cannot assing value to passedDeliveryMethods, because it needs MArray instance or an Array.", + ); } setPassedDeliveryMethods( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.PassedDeliveryMethods + >[], ) { this.passedDeliveryMethods = value; return this; @@ -791,9 +883,11 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * Delivery methods that failed validation for this condition * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods} **/ - #failedDeliveryMethods: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods - >[] = []; + #failedDeliveryMethods: MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods + > + > = MArray.of([]); /** * Delivery methods that failed validation for this condition * @returns {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods} @@ -806,33 +900,64 @@ export class GetSmartClassificationReportOfTheParticularOfferActionRes { * @type {GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods} **/ set failedDeliveryMethods( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods + >[], ) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if ( + value.length > 0 && + value[0] instanceof + GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions + .FailedDeliveryMethods + ) { + this.#failedDeliveryMethods = MArray.of(value); + } else { + this.#failedDeliveryMethods = MArray.of( + value.map( + (item) => + new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods( + item, + ), + ), + ); + } return; } - if ( - value.length > 0 && - value[0] instanceof - GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions - .FailedDeliveryMethods - ) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#failedDeliveryMethods = value; - } else { - this.#failedDeliveryMethods = value.map( - (item) => - new GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods( - item, - ), - ); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#failedDeliveryMethods = mcastValue as any; + return; } + console.warn( + "Cannot assing value to failedDeliveryMethods, because it needs MArray instance or an Array.", + ); } setFailedDeliveryMethods( - value: InstanceType< - typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods - >[], + value: + | MArray< + InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods + > + > + | InstanceType< + typeof GetSmartClassificationReportOfTheParticularOfferActionRes.Conditions.FailedDeliveryMethods + >[], ) { this.failedDeliveryMethods = value; return this; diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/buildUrl.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/buildUrl.ts deleted file mode 100644 index cf08f1cc..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/buildUrl.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Handy tool to create a final callable url, from query string, query params, - * and the actual url. - * @param template - * @param params - * @param qs - * @returns - */ -export function buildUrl( - url: string, - params?: Record, - qs?: URLSearchParams -) { - // Replace :placeholders - if (params) { - Object.entries(params as Record).forEach(([key, value]) => { - url = url.replace( - new RegExp(`:${key}`, "g"), - encodeURIComponent(String(value)) - ); - }); - } - - if (qs && qs instanceof URLSearchParams) { - url += `?${qs.toString()}`; - } else if (qs && Object.keys(qs).length) { - const query = new URLSearchParams( - Object.entries(qs).map(([k, v]) => [k, String(v)]) - ).toString(); - url += `?${query}`; - } - - return url; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/fetchx.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/fetchx.ts deleted file mode 100644 index 774f16b0..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/fetchx.ts +++ /dev/null @@ -1,196 +0,0 @@ -export type TypedRequestInit = Omit< - RequestInit, - "body" | "headers" -> & { - body?: TBody; - headers?: THeaders; -}; -export class TypedResponse extends Response { - override json(): Promise { - return super.json(); - } - result: - | T - | undefined - | ReadableStream> - | null - | string; -} -export async function fetchx< - TResponse = unknown, - TBody = unknown, - THeaders = unknown, ->( - input: RequestInfo | URL, - init?: TypedRequestInit, - ctx?: FetchxContext | null, -): Promise> { - let url = input.toString(); - let reqInit: TypedRequestInit = init || {}; - let res: TypedResponse; - let fetchFn = fetch; - - if (ctx) { - [url, reqInit] = await ctx.apply(url, reqInit); - - if (ctx.fetchOverrideFn) { - fetchFn = ctx.fetchOverrideFn; - } - } - - res = (await fetchFn( - url, - reqInit as RequestInit, - )) as TypedResponse; - - if (ctx) { - res = await ctx.handle(res); - } - return res; -} -type DtoFactory = { new (data: any): T } | ((data: any) => T); -function isConstructor(fn: DtoFactory): fn is { new (data: any): T } { - return ( - typeof fn === "function" && fn.prototype && fn.prototype.constructor === fn - ); -} -export async function handleFetchResponse( - res: TypedResponse, - dto?: DtoFactory, - onMessage?: (msg: any) => void, - signal?: AbortSignal | null, -): Promise<{ done: Promise; response: TypedResponse }> { - const ct = res.headers.get("content-type") || ""; - const cd = res.headers.get("content-disposition") || ""; - if (ct.includes("text/event-stream")) { - return SSEFetch(res, onMessage, signal); - } - if ( - cd.includes("attachment") || - (!ct.includes("json") && !ct.startsWith("text/")) - ) { - (res as any).result = res.body; - } else if (ct.includes("application/json")) { - const json = await res.json(); - if (dto) { - if (isConstructor(dto)) { - (res as any).result = new dto(json); // ✅ class constructor - } else { - (res as any).result = dto(json); // ✅ factory function - } - } else { - (res as any).result = json; - } - } else { - (res as any).result = await res.text(); - } - return { done: Promise.resolve(), response: res as any }; -} -export const SSEFetch = ( - res: TypedResponse, - onMessage?: (ev: MessageEvent) => void, - signal?: AbortSignal | null, -): { response: TypedResponse; done: Promise } => { - if (!res.body) throw new Error("SSE requires readable body"); - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - const done = new Promise((resolve, reject) => { - function readChunk() { - reader - .read() - .then(({ done: finished, value }) => { - if (signal?.aborted) { - reader.cancel(); - return resolve(); // resolve on abort - } - if (finished) return resolve(); // normal end - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split("\n\n"); - buffer = parts.pop() || ""; - for (const part of parts) { - let data = ""; - let event = "message"; - part.split("\n").forEach((line) => { - if (line.startsWith("data:")) data += line.slice(5).trim(); - else if (line.startsWith("event:")) event = line.slice(6).trim(); - }); - if (data) { - if (data === "[DONE]") return resolve(); - onMessage?.(new MessageEvent(event, { data })); - } - } - readChunk(); - }) - .catch((err) => { - if (err.name === "AbortError") resolve(); - else reject(err); - }); - } - readChunk(); - }); - return { response: res, done }; -}; -export class FetchxContext { - constructor( - public baseUrl: string = "", - public defaultHeaders: Record = {}, - public requestInterceptor?: ( - url: string, - init: TypedRequestInit, - ) => - | Promise<[string, TypedRequestInit]> - | [string, TypedRequestInit], - public responseInterceptor?: ( - res: TypedResponse, - ) => Promise>, - /** - * Overrides the browser fetch function, for different purposes. It would recieve the same first 2 arguments as fetch, - * as well as third one of fetchx context. If you pass the fetch itself to override, it should have no effect. - */ - public fetchOverrideFn?: ( - input: RequestInfo | URL, - init?: TypedRequestInit, - ) => Promise, - ) {} - async apply( - url: string, - init: TypedRequestInit, - ): Promise<[string, TypedRequestInit]> { - // prefix baseUrl - if (!/^https?:\/\//.test(url)) { - url = this.baseUrl + url; - } - // merge default headers - (init.headers as unknown) = { - ...this.defaultHeaders, - ...((init.headers as object) || {}), - }; - // call request interceptor if present - if (this.requestInterceptor) { - return this.requestInterceptor(url, init); - } - return [url, init]; - } - async handle(res: TypedResponse): Promise> { - if (this.responseInterceptor) { - return this.responseInterceptor(res); - } - return res; - } - clone(overrides?: Partial): FetchxContext { - return new FetchxContext( - overrides?.baseUrl ?? this.baseUrl, - { ...this.defaultHeaders, ...(overrides?.defaultHeaders || {}) }, - overrides?.requestInterceptor ?? this.requestInterceptor, - overrides?.responseInterceptor ?? this.responseInterceptor, - ); - } -} -export type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; \ No newline at end of file diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/operators.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/operators.ts deleted file mode 100644 index 728da07e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/operators.ts +++ /dev/null @@ -1,173 +0,0 @@ -export class MOne { - private operation: string | null = null; - private selector: S | undefined; - - private content: T | undefined = undefined; - - isNull(): boolean { - return this.content === null; - } - - isSelector(): boolean { - return this.selector !== undefined && this.operation !== null; - } - - get(): T { - return this.content!; - } - - static of(value: T) { - const one = new MOne(); - one.content = value; - - return one; - } - - static select(selector: any) { - const one = new MOne(); - one.selector = selector; - one.operation = "replace"; - - return one; - } - - toJSON() { - // When its explicit replace, it means that we need to pass a selector, so reader will - // be able to replace it via internal mechanism - if (this.operation === "replace") { - return { - __operation: this.operation, - selector: this.selector, - }; - } - - return this.content; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, maybe just giving back one is enough. -export class MOneNullable extends MOne {} - -// Array describes how an incoming list should be applied to an existing one, -// mirroring emigo.Array on the Go side. It lets a PATCH-style payload say -// "replace the whole set" versus "append to the existing set". -// -// On the wire a "replace" is implicit (a bare array), while an "append" is -// tagged with __operation so the reader keeps the existing rows. This keeps -// the payload identical to the Go client/backend generators. -export class MArray { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "replace"; - - return arr; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const arr = new MArray(); - arr.items = items; - arr.operation = "append"; - - return arr; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Array is enough. -export class MArrayNullable extends Array {} - -// Collection mirrors emigo.Collection on the Go side. Structurally it is the -// same as Array — a list carrying a "replace"/"append" operation — but it is a -// distinct field type: a collection holds a list of a target entity, whereas an -// array holds a list of an inline DTO. -export class MCollection { - private operation: "replace" | "append" = "replace"; - private items: T[] = []; - - isAppend(): boolean { - return this.operation === "append"; - } - - isReplace(): boolean { - return this.operation === "replace"; - } - - len(): number { - return this.items.length; - } - - get(): T[] { - return this.items; - } - - // Full replacement — existing rows are cleared before these are applied. - static of(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "replace"; - - return collection; - } - - // Append — existing rows are preserved and these are added alongside them. - static append(items: T[]) { - const collection = new MCollection(); - collection.items = items; - collection.operation = "append"; - - return collection; - } - - toJSON() { - // "replace" is implicit on the wire, so we emit a bare array. Only the - // "append" operation needs the explicit tagged-object form. - if (this.operation === "append") { - return { - __operation: this.operation, - items: this.items, - }; - } - - return this.items; - } -} - -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Collection is enough. -export class CollectionNullable extends MCollection {} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/withPrefix.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts deleted file mode 100644 index 850d7626..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/common/EnvelopeClass.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * To declare a new envelope class, you must follow these rules: - * 1. The constructor must accept any object, which will contain the parsed JSON message - * from a response. - * 2. Envelope classes must provide a function to update the payload. Since payloads are - * type-safe, they must be instantiated and passed to the envelope; the common constructor - * alone is not enough. - * 3. Enveope must have a way to provide the content back actually, in order to create a class out of them. - */ - -export type CreatorSignature = (item: unknown) => T; - -export interface EnvelopeClass { - setCreator(fn: CreatorSignature): this; - inject(data: unknown): this; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts deleted file mode 100644 index 455cdd2e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/flat-array/FlatArray.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; - -// Some responses are returning a flat array, without any other information -// regarding the pagination, etc. They start [{},{}...] style. -// For those which might have a single project which is array but none-standard, -// Use CaptureArray instead. - -export class FlatArray implements EnvelopeClass { - public data: T[] = []; - creator?: CreatorSignature | null = null; - - inject(data: unknown) { - if (!Array.isArray(data)) { - throw new Error( - "FlatArray can only work on flat array items, such as [{},...], and doesn't accept any other type" - ); - } - - if (typeof this.creator !== "undefined") { - this.data = data.map((item) => - (this.creator as CreatorSignature)(item) - ); - } else { - this.data = data; - } - - return this; - } - - setCreator(creator: CreatorSignature) { - this.creator = creator; - - return this; - } - - // Implement thigs here, which would make the flat array to act as an array actually, how can it become - // class instance as an array? -} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts deleted file mode 100644 index 0c078ce3..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/ResponseDto.ts +++ /dev/null @@ -1,1715 +0,0 @@ -import { withPrefix } from "./sdk/common/withPrefix"; -/** - * The base class definition for responseDto - **/ -export class ResponseDto { - /** - * Version of the API used for this response. - * @type {string} - **/ - #apiVersion?: string | null = undefined; - /** - * Version of the API used for this response. - * @returns {string} - **/ - get apiVersion() { - return this.#apiVersion; - } - /** - * Version of the API used for this response. - * @type {string} - **/ - set apiVersion(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#apiVersion = correctType ? value : String(value); - } - setApiVersion(value: string | null | undefined) { - this.apiVersion = value; - return this; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - #context?: string | null = undefined; - /** - * Context string provided by the client or system for request tracking. - * @returns {string} - **/ - get context() { - return this.#context; - } - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - set context(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#context = correctType ? value : String(value); - } - setContext(value: string | null | undefined) { - this.context = value; - return this; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier assigned to the request/response. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - #method?: string | null = undefined; - /** - * Name of the API method invoked. - * @returns {string} - **/ - get method() { - return this.#method; - } - /** - * Name of the API method invoked. - * @type {string} - **/ - set method(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#method = correctType ? value : String(value); - } - setMethod(value: string | null | undefined) { - this.method = value; - return this; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - #params: any = null; - /** - * Parameters sent with the request. - * @returns {any} - **/ - get params() { - return this.#params; - } - /** - * Parameters sent with the request. - * @type {any} - **/ - set params(value: any) { - this.#params = value; - } - setParams(value: any) { - this.params = value; - return this; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - #data!: InstanceType>; - /** - * Main data payload of the response. - * @returns {ResponseDto.Data} - **/ - get data() { - return this.#data; - } - /** - * Main data payload of the response. - * @type {ResponseDto.Data} - **/ - set data(value: InstanceType>) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Data) { - this.#data = value; - } else { - this.#data = new ResponseDto.Data(value); - } - } - setData(value: InstanceType>) { - this.data = value; - return this; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - #error!: InstanceType; - /** - * Error details, if the request failed. - * @returns {ResponseDto.Error} - **/ - get error() { - return this.#error; - } - /** - * Error details, if the request failed. - * @type {ResponseDto.Error} - **/ - set error(value: InstanceType) { - // For objects, the sub type needs to always be instance of the sub class. - if (value instanceof ResponseDto.Error) { - this.#error = value; - } else { - this.#error = new ResponseDto.Error(value); - } - } - setError(value: InstanceType) { - this.error = value; - return this; - } - /** - * The base class definition for data - **/ - static Data = class Data { - /** - * Single item returned by the API. - * @type {any} - **/ - #item: T | null = null; - /** - * Single item returned by the API. - * @returns {T} - **/ - get item(): T | null { - return this.#item; - } - /** - * Single item returned by the API. - * @type {any} - **/ - set item(value: any) { - this.#item = value; - } - setItem(value: any) { - this.item = value; - return this; - } - /** - * List of items returned by the API. - * @type {any} - **/ - #items: T[] = []; - /** - * List of items returned by the API. - * @returns {T[]} - **/ - get items(): T[] { - return this.#items; - } - /** - * List of items returned by the API. - * @type {T[]} - **/ - set items(value: T[]) { - this.#items = value; - } - setItems(value: T[]) { - this.items = value; - return this; - } - /** - * Link to edit this resource. - * @type {string} - **/ - #editLink?: string | null = undefined; - /** - * Link to edit this resource. - * @returns {string} - **/ - get editLink() { - return this.#editLink; - } - /** - * Link to edit this resource. - * @type {string} - **/ - set editLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#editLink = correctType ? value : String(value); - } - setEditLink(value: string | null | undefined) { - this.editLink = value; - return this; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - #selfLink?: string | null = undefined; - /** - * Link to retrieve this resource. - * @returns {string} - **/ - get selfLink() { - return this.#selfLink; - } - /** - * Link to retrieve this resource. - * @type {string} - **/ - set selfLink(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#selfLink = correctType ? value : String(value); - } - setSelfLink(value: string | null | undefined) { - this.selfLink = value; - return this; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - #kind?: string | null = undefined; - /** - * Resource type (kind) identifier. - * @returns {string} - **/ - get kind() { - return this.#kind; - } - /** - * Resource type (kind) identifier. - * @type {string} - **/ - set kind(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#kind = correctType ? value : String(value); - } - setKind(value: string | null | undefined) { - this.kind = value; - return this; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - #fields?: string | null = undefined; - /** - * Selector specifying which fields are included in a partial response. - * @returns {string} - **/ - get fields() { - return this.#fields; - } - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - set fields(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#fields = correctType ? value : String(value); - } - setFields(value: string | null | undefined) { - this.fields = value; - return this; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - #etag?: string | null = undefined; - /** - * ETag of the resource, used for caching/version control. - * @returns {string} - **/ - get etag() { - return this.#etag; - } - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - set etag(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#etag = correctType ? value : String(value); - } - setEtag(value: string | null | undefined) { - this.etag = value; - return this; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - #cursor?: string | null = undefined; - /** - * Cursor for paginated data fetching. - * @returns {string} - **/ - get cursor() { - return this.#cursor; - } - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - set cursor(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#cursor = correctType ? value : String(value); - } - setCursor(value: string | null | undefined) { - this.cursor = value; - return this; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - #id?: string | null = undefined; - /** - * Unique identifier of the resource. - * @returns {string} - **/ - get id() { - return this.#id; - } - /** - * Unique identifier of the resource. - * @type {string} - **/ - set id(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#id = correctType ? value : String(value); - } - setId(value: string | null | undefined) { - this.id = value; - return this; - } - /** - * Language code of the response data. - * @type {string} - **/ - #lang?: string | null = undefined; - /** - * Language code of the response data. - * @returns {string} - **/ - get lang() { - return this.#lang; - } - /** - * Language code of the response data. - * @type {string} - **/ - set lang(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#lang = correctType ? value : String(value); - } - setLang(value: string | null | undefined) { - this.lang = value; - return this; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - #updated?: string | null = undefined; - /** - * Last modification time of the resource. - * @returns {string} - **/ - get updated() { - return this.#updated; - } - /** - * Last modification time of the resource. - * @type {string} - **/ - set updated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#updated = correctType ? value : String(value); - } - setUpdated(value: string | null | undefined) { - this.updated = value; - return this; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - #currentItemCount?: number | null = undefined; - /** - * Number of items in the current response page. - * @returns {number} - **/ - get currentItemCount() { - return this.#currentItemCount; - } - /** - * Number of items in the current response page. - * @type {number} - **/ - set currentItemCount(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#currentItemCount = parsedValue; - } - } - setCurrentItemCount(value: number | null | undefined) { - this.currentItemCount = value; - return this; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - #itemsPerPage?: number | null = undefined; - /** - * Maximum number of items per page. - * @returns {number} - **/ - get itemsPerPage() { - return this.#itemsPerPage; - } - /** - * Maximum number of items per page. - * @type {number} - **/ - set itemsPerPage(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#itemsPerPage = parsedValue; - } - } - setItemsPerPage(value: number | null | undefined) { - this.itemsPerPage = value; - return this; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - #startIndex?: number | null = undefined; - /** - * Index of the first item in the current page. - * @returns {number} - **/ - get startIndex() { - return this.#startIndex; - } - /** - * Index of the first item in the current page. - * @type {number} - **/ - set startIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#startIndex = parsedValue; - } - } - setStartIndex(value: number | null | undefined) { - this.startIndex = value; - return this; - } - /** - * Total number of items available. - * @type {number} - **/ - #totalItems?: number | null = undefined; - /** - * Total number of items available. - * @returns {number} - **/ - get totalItems() { - return this.#totalItems; - } - /** - * Total number of items available. - * @type {number} - **/ - set totalItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalItems = parsedValue; - } - } - setTotalItems(value: number | null | undefined) { - this.totalItems = value; - return this; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - #totalAvailableItems?: number | null = undefined; - /** - * Number of items available for this user/query. - * @returns {number} - **/ - get totalAvailableItems() { - return this.#totalAvailableItems; - } - /** - * Number of items available for this user/query. - * @type {number} - **/ - set totalAvailableItems(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalAvailableItems = parsedValue; - } - } - setTotalAvailableItems(value: number | null | undefined) { - this.totalAvailableItems = value; - return this; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - #pageIndex?: number | null = undefined; - /** - * Current page index in the pagination. - * @returns {number} - **/ - get pageIndex() { - return this.#pageIndex; - } - /** - * Current page index in the pagination. - * @type {number} - **/ - set pageIndex(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#pageIndex = parsedValue; - } - } - setPageIndex(value: number | null | undefined) { - this.pageIndex = value; - return this; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - #totalPages?: number | null = undefined; - /** - * Total number of pages in the pagination. - * @returns {number} - **/ - get totalPages() { - return this.#totalPages; - } - /** - * Total number of pages in the pagination. - * @type {number} - **/ - set totalPages(value: number | null | undefined) { - const correctType = - typeof value === "number" || value === undefined || value === null; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#totalPages = parsedValue; - } - } - setTotalPages(value: number | null | undefined) { - this.totalPages = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.item !== undefined) { - this.item = d.item; - } - if (d.items !== undefined) { - this.items = d.items; - } - if (d.editLink !== undefined) { - this.editLink = d.editLink; - } - if (d.selfLink !== undefined) { - this.selfLink = d.selfLink; - } - if (d.kind !== undefined) { - this.kind = d.kind; - } - if (d.fields !== undefined) { - this.fields = d.fields; - } - if (d.etag !== undefined) { - this.etag = d.etag; - } - if (d.cursor !== undefined) { - this.cursor = d.cursor; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.lang !== undefined) { - this.lang = d.lang; - } - if (d.updated !== undefined) { - this.updated = d.updated; - } - if (d.currentItemCount !== undefined) { - this.currentItemCount = d.currentItemCount; - } - if (d.itemsPerPage !== undefined) { - this.itemsPerPage = d.itemsPerPage; - } - if (d.startIndex !== undefined) { - this.startIndex = d.startIndex; - } - if (d.totalItems !== undefined) { - this.totalItems = d.totalItems; - } - if (d.totalAvailableItems !== undefined) { - this.totalAvailableItems = d.totalAvailableItems; - } - if (d.pageIndex !== undefined) { - this.pageIndex = d.pageIndex; - } - if (d.totalPages !== undefined) { - this.totalPages = d.totalPages; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - item: this.#item, - items: this.#items, - editLink: this.#editLink, - selfLink: this.#selfLink, - kind: this.#kind, - fields: this.#fields, - etag: this.#etag, - cursor: this.#cursor, - id: this.#id, - lang: this.#lang, - updated: this.#updated, - currentItemCount: this.#currentItemCount, - itemsPerPage: this.#itemsPerPage, - startIndex: this.#startIndex, - totalItems: this.#totalItems, - totalAvailableItems: this.#totalAvailableItems, - pageIndex: this.#pageIndex, - totalPages: this.#totalPages, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - item: "item", - items: "items", - editLink: "editLink", - selfLink: "selfLink", - kind: "kind", - fields: "fields", - etag: "etag", - cursor: "cursor", - id: "id", - lang: "lang", - updated: "updated", - currentItemCount: "currentItemCount", - itemsPerPage: "itemsPerPage", - startIndex: "startIndex", - totalItems: "totalItems", - totalAvailableItems: "totalAvailableItems", - pageIndex: "pageIndex", - totalPages: "totalPages", - }; - } - /** - * Creates an instance of ResponseDto.Data, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.DataType) { - return new ResponseDto.Data(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Data, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep>, - ) { - return new ResponseDto.Data(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto.Data({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Data(this.toJSON()); - } - }; - /** - * The base class definition for error - **/ - static Error = class Error { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - #code: number = 0; - /** - * Numeric error code representing the failure. - * @returns {number} - **/ - get code() { - return this.#code; - } - /** - * Numeric error code representing the failure. - * @type {number} - **/ - set code(value: number) { - const correctType = typeof value === "number"; - const parsedValue = correctType ? value : Number(value); - if (!Number.isNaN(parsedValue)) { - this.#code = parsedValue; - } - } - setCode(value: number) { - this.code = value; - return this; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - #message: string = ""; - /** - * Human-readable explanation of the error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the error. - * @type {string} - **/ - set message(value: string) { - this.#message = String(value); - } - setMessage(value: string) { - this.message = value; - return this; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - #messageTranslated: string = ""; - /** - * Localized/translated version of the error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the error message. - * @type {string} - **/ - set messageTranslated(value: string) { - this.#messageTranslated = String(value); - } - setMessageTranslated(value: string) { - this.messageTranslated = value; - return this; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - #errors: InstanceType[] = []; - /** - * Detailed list of error objects. - * @returns {ResponseDto.Error.Errors} - **/ - get errors() { - return this.#errors; - } - /** - * Detailed list of error objects. - * @type {ResponseDto.Error.Errors} - **/ - set errors(value: InstanceType[]) { - // For arrays, you only can pass arrays to the object - if (!Array.isArray(value)) { - return; - } - if (value.length > 0 && value[0] instanceof ResponseDto.Error.Errors) { - this.#errors = value; - } else { - this.#errors = value.map((item) => new ResponseDto.Error.Errors(item)); - } - } - setErrors(value: InstanceType[]) { - this.errors = value; - return this; - } - /** - * The base class definition for errors - **/ - static Errors = class Errors { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - #domain?: string | null = undefined; - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @returns {string} - **/ - get domain() { - return this.#domain; - } - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - set domain(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#domain = correctType ? value : String(value); - } - setDomain(value: string | null | undefined) { - this.domain = value; - return this; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - #reason?: string | null = undefined; - /** - * Reason identifier for the error. - * @returns {string} - **/ - get reason() { - return this.#reason; - } - /** - * Reason identifier for the error. - * @type {string} - **/ - set reason(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#reason = correctType ? value : String(value); - } - setReason(value: string | null | undefined) { - this.reason = value; - return this; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - #message?: string | null = undefined; - /** - * Human-readable explanation of the sub-error. - * @returns {string} - **/ - get message() { - return this.#message; - } - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - set message(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#message = correctType ? value : String(value); - } - setMessage(value: string | null | undefined) { - this.message = value; - return this; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - #messageTranslated?: string | null = undefined; - /** - * Localized/translated version of the sub-error message. - * @returns {string} - **/ - get messageTranslated() { - return this.#messageTranslated; - } - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - set messageTranslated(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#messageTranslated = correctType ? value : String(value); - } - setMessageTranslated(value: string | null | undefined) { - this.messageTranslated = value; - return this; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - #location?: string | null = undefined; - /** - * Field or parameter in which the error occurred. - * @returns {string} - **/ - get location() { - return this.#location; - } - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - set location(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#location = correctType ? value : String(value); - } - setLocation(value: string | null | undefined) { - this.location = value; - return this; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - #locationType?: string | null = undefined; - /** - * Type of location (e.g., parameter, header). - * @returns {string} - **/ - get locationType() { - return this.#locationType; - } - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - set locationType(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#locationType = correctType ? value : String(value); - } - setLocationType(value: string | null | undefined) { - this.locationType = value; - return this; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - #extendedHelp?: string | null = undefined; - /** - * URL linking to additional documentation about the error. - * @returns {string} - **/ - get extendedHelp() { - return this.#extendedHelp; - } - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - set extendedHelp(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#extendedHelp = correctType ? value : String(value); - } - setExtendedHelp(value: string | null | undefined) { - this.extendedHelp = value; - return this; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - #sendReport?: string | null = undefined; - /** - * URL to submit a report for this error. - * @returns {string} - **/ - get sendReport() { - return this.#sendReport; - } - /** - * URL to submit a report for this error. - * @type {string} - **/ - set sendReport(value: string | null | undefined) { - const correctType = - typeof value === "string" || value === undefined || value === null; - this.#sendReport = correctType ? value : String(value); - } - setSendReport(value: string | null | undefined) { - this.sendReport = value; - return this; - } - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.domain !== undefined) { - this.domain = d.domain; - } - if (d.reason !== undefined) { - this.reason = d.reason; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.location !== undefined) { - this.location = d.location; - } - if (d.locationType !== undefined) { - this.locationType = d.locationType; - } - if (d.extendedHelp !== undefined) { - this.extendedHelp = d.extendedHelp; - } - if (d.sendReport !== undefined) { - this.sendReport = d.sendReport; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - domain: this.#domain, - reason: this.#reason, - message: this.#message, - messageTranslated: this.#messageTranslated, - location: this.#location, - locationType: this.#locationType, - extendedHelp: this.#extendedHelp, - sendReport: this.#sendReport, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - domain: "domain", - reason: "reason", - message: "message", - messageTranslated: "messageTranslated", - location: "location", - locationType: "locationType", - extendedHelp: "extendedHelp", - sendReport: "sendReport", - }; - } - /** - * Creates an instance of ResponseDto.Error.Errors, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType.ErrorsType) { - return new ResponseDto.Error.Errors(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error.Errors, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with( - partialDtoObject: PartialDeep, - ) { - return new ResponseDto.Error.Errors(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error.Errors({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error.Errors(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial; - if (d.code !== undefined) { - this.code = d.code; - } - if (d.message !== undefined) { - this.message = d.message; - } - if (d.messageTranslated !== undefined) { - this.messageTranslated = d.messageTranslated; - } - if (d.errors !== undefined) { - this.errors = d.errors; - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - code: this.#code, - message: this.#message, - messageTranslated: this.#messageTranslated, - errors: this.#errors, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - code: "code", - message: "message", - messageTranslated: "messageTranslated", - errors$: "errors", - get errors() { - return withPrefix( - "error.errors[:i]", - ResponseDto.Error.Errors.Fields, - ); - }, - }; - } - /** - * Creates an instance of ResponseDto.Error, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType.ErrorType) { - return new ResponseDto.Error(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto.Error, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep) { - return new ResponseDto.Error(partialDtoObject); - } - copyWith( - partial: PartialDeep, - ): InstanceType { - return new ResponseDto.Error({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto.Error(this.toJSON()); - } - }; - constructor(data: unknown = undefined) { - if (data === null || data === undefined) { - this.#lateInitFields(); - return; - } - if (typeof data === "string") { - this.applyFromObject(JSON.parse(data)); - } else if (this.#isJsonAppliable(data)) { - this.applyFromObject(data); - } else { - throw new Error( - "Instance cannot be created on an unknown value, check the content being passed. got: " + - typeof data, - ); - } - } - #isJsonAppliable(obj: unknown) { - const g = globalThis as unknown as { Buffer: any; Blob: any }; - const isBuffer = - typeof g.Buffer !== "undefined" && - typeof g.Buffer.isBuffer === "function" && - g.Buffer.isBuffer(obj); - const isBlob = typeof g.Blob !== "undefined" && obj instanceof g.Blob; - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - !isBuffer && - !(obj instanceof ArrayBuffer) && - !isBlob - ); - } - /** - * casts the fields of a javascript object into the class properties one by one - **/ - applyFromObject(data = {}) { - const d = data as Partial>; - if (d.apiVersion !== undefined) { - this.apiVersion = d.apiVersion; - } - if (d.context !== undefined) { - this.context = d.context; - } - if (d.id !== undefined) { - this.id = d.id; - } - if (d.method !== undefined) { - this.method = d.method; - } - if (d.params !== undefined) { - this.params = d.params; - } - if (d.data !== undefined) { - this.data = d.data; - } - if (d.error !== undefined) { - this.error = d.error; - } - this.#lateInitFields(data); - } - /** - * These are the class instances, which need to be initialised, regardless of the constructor incoming data - **/ - #lateInitFields(data = {}) { - const d = data as Partial>; - if (!(d.data instanceof ResponseDto.Data)) { - this.data = new ResponseDto.Data(d.data || {}); - } - if (!(d.error instanceof ResponseDto.Error)) { - this.error = new ResponseDto.Error(d.error || {}); - } - } - /** - * Special toJSON override, since the field are private, - * Json stringify won't see them unless we mention it explicitly. - **/ - toJSON() { - return { - apiVersion: this.#apiVersion, - context: this.#context, - id: this.#id, - method: this.#method, - params: this.#params, - data: this.#data, - error: this.#error, - }; - } - toString() { - return JSON.stringify(this); - } - static get Fields() { - return { - apiVersion: "apiVersion", - context: "context", - id: "id", - method: "method", - params: "params", - data$: "data", - get data() { - return withPrefix("data", ResponseDto.Data.Fields); - }, - error$: "error", - get error() { - return withPrefix("error", ResponseDto.Error.Fields); - }, - }; - } - /** - * Creates an instance of ResponseDto, and possibleDtoObject - * needs to satisfy the type requirement fully, otherwise typescript compile would - * be complaining. - **/ - static from(possibleDtoObject: ResponseDtoType) { - return new ResponseDto(possibleDtoObject); - } - /** - * Creates an instance of ResponseDto, and partialDtoObject - * needs to satisfy the type, but partially, and rest of the content would - * be constructed according to data types and nullability. - **/ - static with(partialDtoObject: PartialDeep>) { - return new ResponseDto(partialDtoObject); - } - copyWith( - partial: PartialDeep>, - ): InstanceType { - return new ResponseDto({ ...this.toJSON(), ...partial }); - } - clone(): InstanceType { - return new ResponseDto(this.toJSON()); - } -} -export abstract class ResponseDtoFactory { - abstract create(data: unknown): ResponseDto; -} -type PartialDeep = { - [P in keyof T]?: T[P] extends Array - ? Array> - : T[P] extends object - ? PartialDeep - : T[P]; -}; -/** - * The base type definition for responseDto - **/ -export type ResponseDtoType = { - /** - * Version of the API used for this response. - * @type {string} - **/ - apiVersion?: string; - /** - * Context string provided by the client or system for request tracking. - * @type {string} - **/ - context?: string; - /** - * Unique identifier assigned to the request/response. - * @type {string} - **/ - id?: string; - /** - * Name of the API method invoked. - * @type {string} - **/ - method?: string; - /** - * Parameters sent with the request. - * @type {any} - **/ - params: any; - /** - * Main data payload of the response. - * @type {ResponseDtoType.DataType} - **/ - data: ResponseDtoType.DataType; - /** - * Error details, if the request failed. - * @type {ResponseDtoType.ErrorType} - **/ - error: ResponseDtoType.ErrorType; -}; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ResponseDtoType { - /** - * The base type definition for dataType - **/ - export type DataType = { - /** - * Single item returned by the API. - * @type {any} - **/ - item2: T; - /** - * List of items returned by the API. - * @type {any} - **/ - items: any; - /** - * Link to edit this resource. - * @type {string} - **/ - editLink?: string; - /** - * Link to retrieve this resource. - * @type {string} - **/ - selfLink?: string; - /** - * Resource type (kind) identifier. - * @type {string} - **/ - kind?: string; - /** - * Selector specifying which fields are included in a partial response. - * @type {string} - **/ - fields?: string; - /** - * ETag of the resource, used for caching/version control. - * @type {string} - **/ - etag?: string; - /** - * Cursor for paginated data fetching. - * @type {string} - **/ - cursor?: string; - /** - * Unique identifier of the resource. - * @type {string} - **/ - id?: string; - /** - * Language code of the response data. - * @type {string} - **/ - lang?: string; - /** - * Last modification time of the resource. - * @type {string} - **/ - updated?: string; - /** - * Number of items in the current response page. - * @type {number} - **/ - currentItemCount?: number; - /** - * Maximum number of items per page. - * @type {number} - **/ - itemsPerPage?: number; - /** - * Index of the first item in the current page. - * @type {number} - **/ - startIndex?: number; - /** - * Total number of items available. - * @type {number} - **/ - totalItems?: number; - /** - * Number of items available for this user/query. - * @type {number} - **/ - totalAvailableItems?: number; - /** - * Current page index in the pagination. - * @type {number} - **/ - pageIndex?: number; - /** - * Total number of pages in the pagination. - * @type {number} - **/ - totalPages?: number; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace DataType {} - /** - * The base type definition for errorType - **/ - export type ErrorType = { - /** - * Numeric error code representing the failure. - * @type {number} - **/ - code: number; - /** - * Human-readable explanation of the error. - * @type {string} - **/ - message: string; - /** - * Localized/translated version of the error message. - * @type {string} - **/ - messageTranslated: string; - /** - * Detailed list of error objects. - * @type {ResponseDtoType.ErrorType.ErrorsType[]} - **/ - errors: ResponseDtoType.ErrorType.ErrorsType[]; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorType { - /** - * The base type definition for errorsType - **/ - export type ErrorsType = { - /** - * Logical grouping of the error (e.g., global, usageLimits). - * @type {string} - **/ - domain?: string; - /** - * Reason identifier for the error. - * @type {string} - **/ - reason?: string; - /** - * Human-readable explanation of the sub-error. - * @type {string} - **/ - message?: string; - /** - * Localized/translated version of the sub-error message. - * @type {string} - **/ - messageTranslated?: string; - /** - * Field or parameter in which the error occurred. - * @type {string} - **/ - location?: string; - /** - * Type of location (e.g., parameter, header). - * @type {string} - **/ - locationType?: string; - /** - * URL linking to additional documentation about the error. - * @type {string} - **/ - extendedHelp?: string; - /** - * URL to submit a report for this error. - * @type {string} - **/ - sendReport?: string; - }; - // eslint-disable-next-line @typescript-eslint/no-namespace - export namespace ErrorsType {} - } -} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json deleted file mode 100644 index 7a3dc447..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "sdk", - "version": "1.0.0", - "description": "Auto-generated package.json", - "main": "index.js", - "scripts": { - "build": "echo 'build script here'", - "test": "echo 'test script here'" - }, - "dependencies": { - "@types/qs": "^6.14.0", - "qs": "^6.14.0" - } -} \ No newline at end of file diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts deleted file mode 100644 index 8630562e..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/generated/sdk/common/withPrefix.ts +++ /dev/null @@ -1,22 +0,0 @@ -export function withPrefix>( - prefix: string, - fields: T -): T { - const out: Record = {}; - for (const [k, v] of Object.entries(fields)) { - if (typeof v === "string") { - out[k] = `${prefix}.${v}`; - } else if (typeof v === "object" && v !== null) { - out[k] = v; - } - } - return out as T; -} - -export function at(source: string, ...args: number[]): string { - args.forEach((item) => { - source = source.replace("[:i]", `[${item}]`); - }); - - return source; -} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml deleted file mode 100644 index 0dcb101c..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/google-envelop.emi.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: googleEnvelop -description: - Generating envelop API responses using Emi itself. - Emi codegen is so strong that can generate deep classes in javascript which could be used - in itself and in this example we are doing it. - - All responses can be wrapped in google json styleguide, which gives extream consistency. - -dtos: - - name: response - fields: - - name: apiVersion - type: string? - description: Version of the API used for this response. - - name: context - type: string? - description: Context string provided by the client or system for request tracking. - - name: id - type: string? - description: Unique identifier assigned to the request/response. - - name: method - type: string? - description: Name of the API method invoked. - - name: params - type: any - description: Parameters sent with the request. - - name: data - type: object - description: Main data payload of the response. - fields: - - name: item - type: any - description: Single item returned by the API. - - name: items - type: any - description: List of items returned by the API. - - name: editLink - type: string? - description: Link to edit this resource. - - name: selfLink - type: string? - description: Link to retrieve this resource. - - name: kind - type: string? - description: Resource type (kind) identifier. - - name: fields - type: string? - description: Selector specifying which fields are included in a partial response. - - name: etag - type: string? - description: ETag of the resource, used for caching/version control. - - name: cursor - type: string? - description: Cursor for paginated data fetching. - - name: id - type: string? - description: Unique identifier of the resource. - - name: lang - type: string? - description: Language code of the response data. - - name: updated - type: string? - description: Last modification time of the resource. - - name: currentItemCount - type: int? - description: Number of items in the current response page. - - name: itemsPerPage - type: int? - description: Maximum number of items per page. - - name: startIndex - type: int? - description: Index of the first item in the current page. - - name: totalItems - type: int? - description: Total number of items available. - - name: totalAvailableItems - type: int? - description: Number of items available for this user/query. - - name: pageIndex - type: int? - description: Current page index in the pagination. - - name: totalPages - type: int? - description: Total number of pages in the pagination. - - name: error - type: object - description: Error details, if the request failed. - fields: - - name: code - type: int - description: Numeric error code representing the failure. - - name: message - type: string - description: Human-readable explanation of the error. - - name: messageTranslated - type: string - description: Localized/translated version of the error message. - - name: errors - type: array - description: Detailed list of error objects. - fields: - - name: domain - type: string? - description: Logical grouping of the error (e.g., global, usageLimits). - - name: reason - type: string? - description: Reason identifier for the error. - - name: message - type: string? - description: Human-readable explanation of the sub-error. - - name: messageTranslated - type: string? - description: Localized/translated version of the sub-error message. - - name: location - type: string? - description: Field or parameter in which the error occurred. - - name: locationType - type: string? - description: Type of location (e.g., parameter, header). - - name: extendedHelp - type: string? - description: URL linking to additional documentation about the error. - - name: sendReport - type: string? - description: URL to submit a report for this error. diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts deleted file mode 100644 index 2fc2601b..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/google-json-style-guide/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { CreatorSignature, EnvelopeClass } from "../common/EnvelopeClass"; -import { ResponseDto } from "./generated/ResponseDto"; -// Use this class to generate a GResponse. -export class GResponse extends ResponseDto implements EnvelopeClass { - creator?: CreatorSignature | null; - constructor(data?: unknown) { - super(data); - } - setCreator(fn: CreatorSignature) { - this.creator = fn; - return this; - } - /** - * GResponse can have data.item or data.items - * We create that based on incoming data tpye, so there is no need for 2 different - * classes, one for array and other for singular - * @param data - * @returns - */ - inject(body: any): this { - this.applyFromObject(body); - if ((body as any)?.data) { - if (!this.data) { - this.setData({} as any); - } - if ( - Array.isArray(body?.data.items) && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItems( - body?.data?.items?.map((item: unknown) => this.creator?.(item)), - ); - } else if ( - typeof body?.data?.item === "object" && - typeof this.creator !== "undefined" && - this.creator !== null - ) { - this.data?.setItem(this.creator(body?.data?.item)); - } else { - this.data?.setItem(body?.data?.item); - } - } - return this; - } -} diff --git a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/index.ts b/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/index.ts deleted file mode 100644 index 63d3ef26..00000000 --- a/examples/allegro-sdk/typescript/gen/offer/user-offer-information/sdk/envelopes/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./google-json-style-guide/index"; -export * from "./flat-array/FlatArray"; diff --git a/examples/emi-web/src/content/docs/js/emi-javascript-web-socket.mdx b/examples/emi-web/src/content/docs/js/emi-javascript-web-socket.mdx index 19597011..d9732026 100644 --- a/examples/emi-web/src/content/docs/js/emi-javascript-web-socket.mdx +++ b/examples/emi-web/src/content/docs/js/emi-javascript-web-socket.mdx @@ -81,15 +81,14 @@ export class UserStreamAction { static NewUrl = (qs?: URLSearchParams) => buildUrl(UserStreamAction.URL, undefined, qs); static Method = "reactive"; - static Create = (overrideUrl?: string, qs?: URLSearchParams) => { + static Create = (overrideUrl?: string, qs?: URLSearchParams, options) => { const url = overrideUrl ?? UserStreamAction.NewUrl(qs); - return new WebSocketX( - url, - undefined, - { - MessageFactoryClass: UserStreamActionRes, - }, - ); + const Cls = options?.SocketClass + ? options.SocketClass + : WebSocketX; + return new Cls(url, undefined, { + MessageFactoryClass: UserStreamActionRes, + }); }; static Definition = { name: "userStream", diff --git a/examples/in-browser-server/browser/WebSocketWasm.js b/examples/in-browser-server/browser/WebSocketWasm.js new file mode 100644 index 00000000..b1cec436 --- /dev/null +++ b/examples/in-browser-server/browser/WebSocketWasm.js @@ -0,0 +1,93 @@ +// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the +// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for +// `new WebSocketWasm(url)` and the rest of your code is identical: readyState, +// onopen/onmessage/onclose/onerror, addEventListener, send(), close(). +// +// It is NOT a network client — there is no handshake and no socket. The +// constructor's URL is only used for its pathname (to pick the reactor handler) +// and query string; the host is ignored. +export class WebSocketWasm extends EventTarget { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + + constructor(url, _protocols) { + super(); + this.url = url; + this.readyState = WebSocketWasm.CONNECTING; + this.onopen = null; + this.onmessage = null; + this.onerror = null; + this.onclose = null; + this._id = -1; + + const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse + const path = u.pathname; + const query = u.search.replace(/^\?/, ""); + + // Defer so listeners attached right after `new` still catch 'open', exactly + // like the native async connect. + queueMicrotask(() => this._open(path, query)); + } + + _open(path, query) { + const onMessage = (data) => { + const ev = new MessageEvent("message", { data }); + this.onmessage?.(ev); + this.dispatchEvent(ev); + }; + const onClose = (reason) => { + if (this.readyState === WebSocketWasm.CLOSED) return; + this.readyState = WebSocketWasm.CLOSED; + const ev = new CloseEvent("close", { reason, code: 1000, wasClean: true }); + this.onclose?.(ev); + this.dispatchEvent(ev); + }; + + if (typeof window.wasmWsOpen !== "function") { + return this._fail("reactor not ready (window.wasmWsOpen missing)"); + } + + this._id = window.wasmWsOpen(path, query, onMessage, onClose); + if (this._id < 0) { + return this._fail(`no reactive handler registered for "${path}"`); + } + + this.readyState = WebSocketWasm.OPEN; + const ev = new Event("open"); + this.onopen?.(ev); + this.dispatchEvent(ev); + } + + _fail(message) { + this.readyState = WebSocketWasm.CLOSED; + const err = new Event("error"); + err.message = message; + this.onerror?.(err); + this.dispatchEvent(err); + const close = new CloseEvent("close", { reason: message, code: 1006, wasClean: false }); + this.onclose?.(close); + this.dispatchEvent(close); + } + + send(data) { + if (this.readyState !== WebSocketWasm.OPEN) { + throw new DOMException("WebSocketWasm is not open", "InvalidStateError"); + } + // Strings pass through; everything else is stringified for now. Real binary + // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work. + window.wasmWsSend(this._id, typeof data === "string" ? data : String(data)); + } + + close(_code, _reason) { + if ( + this.readyState === WebSocketWasm.CLOSING || + this.readyState === WebSocketWasm.CLOSED + ) { + return; + } + this.readyState = WebSocketWasm.CLOSING; + if (this._id >= 0) window.wasmWsClose(this._id); + } +} diff --git a/examples/in-browser-server/browser/gen/ChatAction.js b/examples/in-browser-server/browser/gen/ChatAction.js new file mode 100644 index 00000000..98dbcb0f --- /dev/null +++ b/examples/in-browser-server/browser/gen/ChatAction.js @@ -0,0 +1,28 @@ +import { WebSocketX } from "./sdk/common/WebSocketX.js"; +import { buildUrl } from "./sdk/common/buildUrl.js"; +/** + * Action to communicate with the action chat + */ +/** + * ChatAction + */ +export class ChatAction { + // + static URL = "/chat"; + static NewUrl = (qs) => buildUrl(ChatAction.URL, undefined, qs); + static Method = "reactive"; + static Create = (overrideUrl, qs, options) => { + const url = overrideUrl ?? ChatAction.NewUrl(qs); + const Cls = options?.SocketClass ? options.SocketClass : WebSocketX; + return new Cls(url, undefined, { + MessageFactoryClass: undefined, + }); + }; + static Definition = { + name: "chat", + url: "/chat", + method: "reactive", + description: + "A Reactive chating application, that returns length of strings you've typed.", + }; +} diff --git a/examples/in-browser-server/browser/gen/CreateUserAction.js b/examples/in-browser-server/browser/gen/CreateUserAction.js index b41082ee..fb4c761e 100644 --- a/examples/in-browser-server/browser/gen/CreateUserAction.js +++ b/examples/in-browser-server/browser/gen/CreateUserAction.js @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators.js"; import { buildUrl } from "./sdk/common/buildUrl.js"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx.js"; /** diff --git a/examples/in-browser-server/browser/gen/DeleteUserAction.js b/examples/in-browser-server/browser/gen/DeleteUserAction.js index 239477ca..85d74227 100644 --- a/examples/in-browser-server/browser/gen/DeleteUserAction.js +++ b/examples/in-browser-server/browser/gen/DeleteUserAction.js @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators.js"; import { buildUrl } from "./sdk/common/buildUrl.js"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx.js"; /** diff --git a/examples/in-browser-server/browser/gen/ListUsersAction.js b/examples/in-browser-server/browser/gen/ListUsersAction.js index 9e1e415f..a1dd2cfc 100644 --- a/examples/in-browser-server/browser/gen/ListUsersAction.js +++ b/examples/in-browser-server/browser/gen/ListUsersAction.js @@ -1,11 +1,4 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators.js"; +import { MArray } from "./sdk/common/operators.js"; import { buildUrl } from "./sdk/common/buildUrl.js"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx.js"; import { withPrefix } from "./sdk/common/withPrefix.js"; @@ -86,7 +79,7 @@ export class ListUsersActionRes { * * @type {ListUsersActionRes.Users} **/ - #users = []; + #users = MArray.of([]); /** * * @returns {ListUsersActionRes.Users} @@ -99,14 +92,33 @@ export class ListUsersActionRes { * @type {ListUsersActionRes.Users} **/ set users(value) { - if (!Array.isArray(value) && !(value instanceof MCollection)) { + // When the passed value is already an array, we check if we need to + // cast the inner items into class instance. + if (Array.isArray(value)) { + if (value.length > 0 && value[0] instanceof ListUsersActionRes.Users) { + this.#users = MArray.of(value); + } else { + this.#users = MArray.of( + value.map((item) => new ListUsersActionRes.Users(item)), + ); + } return; } - if (value.length > 0 && value[0] instanceof ListUsersActionRes.Users) { + // If the instance is already an MArray, we assume it's all good. + if (value instanceof MArray) { this.#users = value; - } else { - this.#users = value.map((item) => new ListUsersActionRes.Users(item)); + return; + } + // If the value is not array, and is not a MArray, we need to be consider, + // it might be eligible to be casted into MArray. + const { ok, value: mcastValue } = MArray.cast(value); + if (ok) { + this.#users = mcastValue; + return; } + console.warn( + "Cannot assing value to users, because it needs MArray instance or an Array.", + ); } setUsers(value) { this.users = value; diff --git a/examples/in-browser-server/browser/gen/SubstringAction.js b/examples/in-browser-server/browser/gen/SubstringAction.js index 56f06c57..87dc0da0 100644 --- a/examples/in-browser-server/browser/gen/SubstringAction.js +++ b/examples/in-browser-server/browser/gen/SubstringAction.js @@ -1,11 +1,3 @@ -import { - MArray, - MArrayNullable, - MCollection, - MCollectionNullable, - MOne, - MOneNullable, -} from "./sdk/common/operators.js"; import { buildUrl } from "./sdk/common/buildUrl.js"; import { fetchx, handleFetchResponse } from "./sdk/common/fetchx.js"; /** diff --git a/examples/in-browser-server/browser/gen/sdk/common/URLSearchParamsX.js b/examples/in-browser-server/browser/gen/sdk/common/URLSearchParamsX.js new file mode 100644 index 00000000..bf658faf --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/common/URLSearchParamsX.js @@ -0,0 +1,135 @@ +import { stringify, parse } from "qs"; +/** + * Extended URLSearchParams that stores data in a nested object + * and keeps compatibility with URLSearchParams methods. + */ +export class URLSearchParamsX extends URLSearchParams { + constructor(init) { + super(init); + /** Internal data store */ + this.data = {}; + if (init) { + if (typeof init === "string") { + Object.assign(this.data, parse(init)); + } + else if (init instanceof URLSearchParams) { + Object.assign(this.data, parse(init.toString())); + } + else if (Array.isArray(init)) { + init.forEach(([k, v]) => (this.data[k] = v)); + } + else { + Object.assign(this.data, init); + } + } + } + /** Remove a key from the store */ + delete(name) { + delete this.data[name]; + } + /** Append a value to an array or create a new array */ + append(name, value) { + if (this.data[name] === undefined) + this.data[name] = value; + else if (Array.isArray(this.data[name])) + this.data[name].push(value); + else + this.data[name] = [this.data[name], value]; + } + /** Get an iterator of top-level keys */ + keys() { + const obj = this.data; + return (function* () { + for (const key of Object.keys(obj)) { + yield key; + } + return undefined; + })(); + } + /** Number of top-level keys */ + get size() { + return Object.keys(this.data).length; + } + /** Sort top-level keys */ + sort() { + const sorted = {}; + Object.keys(this.data) + .sort() + .forEach((key) => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + sorted[key] = this.data[key]; + }); + this.data = sorted; + } + /** Get an iterator of top-level values */ + values() { + const obj = this.data; + return (function* () { + for (const key of Object.keys(obj)) { + const val = obj[key]; + // Make sure val is string + yield String(val); + } + return undefined; + })(); + } + /** Get a single value by key */ + get(name) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const val = this.data[name]; + if (val == null) + return null; + return Array.isArray(val) ? String(val[0]) : String(val); + } + /** Check if key exists */ + has(name) { + return this.data[name] !== undefined; + } + /** Iterate over top-level keys and values */ + forEach( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callbackfn) { + for (const key of Object.keys(this.data)) { + callbackfn(this.data[key], key, this); + } + } + /** Get all values for a key as array */ + getAll(name) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const val = this.data[name]; + if (val === undefined) + return []; + return Array.isArray(val) ? val.map(String) : [String(val)]; + } + /** Get an iterator of key/value pairs (flattened) */ + entries() { + const params = new URLSearchParams(stringify(this.data)); + return params.entries(); + } + /** Convert to query string */ + toString() { + return stringify(this.data); + } + /** Set a key to a value */ + set(name, value) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.data[name] = value; + return this; + } + /** Convert entries to plain object */ + toObject() { + return Object.fromEntries(this.entries()); + } + // eslint-disable-next-line no-unused-private-class-members + getTyped(key, type) { + const val = this.get(key); + if (val == null) + return null; + const t = type.toLowerCase(); + if (t.includes("number")) + return Number(val); + if (t.includes("bool")) + return val === "true"; + return val; + } +} diff --git a/examples/in-browser-server/browser/gen/sdk/common/WebSocketWasm.js b/examples/in-browser-server/browser/gen/sdk/common/WebSocketWasm.js new file mode 100644 index 00000000..e8cb215e --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/common/WebSocketWasm.js @@ -0,0 +1,95 @@ +// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the +// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for +// `new WebSocketWasm(url)` and the rest of your code is identical: readyState, +// onopen/onmessage/onclose/onerror, addEventListener, send(), close(). +// +// It is NOT a network client — there is no handshake and no socket. The +// constructor's URL is only used for its pathname (to pick the reactor handler) +// and query string; the host is ignored. +export class WebSocketWasm extends EventTarget { + constructor(url, _protocols) { + super(); + this.url = url; + this.readyState = WebSocketWasm.CONNECTING; + this.onopen = null; + this.onmessage = null; + this.onerror = null; + this.onclose = null; + this._id = -1; + const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse + const path = u.pathname; + const query = u.search.replace(/^\?/, ""); + // Defer so listeners attached right after `new` still catch 'open', exactly + // like the native async connect. + queueMicrotask(() => this._open(path, query)); + } + _open(path, query) { + var _a; + const onMessage = (data) => { + var _a; + const ev = new MessageEvent("message", { data }); + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, ev); + this.dispatchEvent(ev); + }; + const onClose = (reason) => { + var _a; + if (this.readyState === WebSocketWasm.CLOSED) + return; + this.readyState = WebSocketWasm.CLOSED; + const ev = new CloseEvent("close", { + reason, + code: 1000, + wasClean: true, + }); + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this, ev); + this.dispatchEvent(ev); + }; + if (typeof window.wasmWsOpen !== "function") { + return this._fail("reactor not ready (window.wasmWsOpen missing)"); + } + this._id = window.wasmWsOpen(path, query, onMessage, onClose); + if (this._id < 0) { + return this._fail(`no reactive handler registered for "${path}"`); + } + this.readyState = WebSocketWasm.OPEN; + const ev = new Event("open"); + (_a = this.onopen) === null || _a === void 0 ? void 0 : _a.call(this, ev); + this.dispatchEvent(ev); + } + _fail(message) { + var _a, _b; + this.readyState = WebSocketWasm.CLOSED; + const err = new Event("error"); + err.message = message; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); + this.dispatchEvent(err); + const close = new CloseEvent("close", { + reason: message, + code: 1006, + wasClean: false, + }); + (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this, close); + this.dispatchEvent(close); + } + send(data) { + if (this.readyState !== WebSocketWasm.OPEN) { + throw new DOMException("WebSocketWasm is not open", "InvalidStateError"); + } + // Strings pass through; everything else is stringified for now. Real binary + // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work. + window.wasmWsSend(this._id, typeof data === "string" ? data : String(data)); + } + close(_code, _reason) { + if (this.readyState === WebSocketWasm.CLOSING || + this.readyState === WebSocketWasm.CLOSED) { + return; + } + this.readyState = WebSocketWasm.CLOSING; + if (this._id >= 0) + window.wasmWsClose(this._id); + } +} +WebSocketWasm.CONNECTING = 0; +WebSocketWasm.OPEN = 1; +WebSocketWasm.CLOSING = 2; +WebSocketWasm.CLOSED = 3; diff --git a/examples/in-browser-server/browser/gen/sdk/common/WebSocketX.js b/examples/in-browser-server/browser/gen/sdk/common/WebSocketX.js new file mode 100644 index 00000000..3dd0a7d4 --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/common/WebSocketX.js @@ -0,0 +1,72 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _WebSocketX_factoryCls; +export class WebSocketX extends WebSocket { + constructor(url, protocols, options) { + super(url, protocols); + _WebSocketX_factoryCls.set(this, void 0); + this.sendRaw = super.send.bind(this); + this.addEventListenerRaw = super.addEventListener.bind(this); + if (options === null || options === void 0 ? void 0 : options.MessageFactoryClass) { + __classPrivateFieldSet(this, _WebSocketX_factoryCls, options.MessageFactoryClass, "f"); + } + } + set onmessage(fn) { + if (fn) { + this.addEventListener("message", fn); + } + else { + super.onmessage = null; + } + } + get onmessage() { + return super.onmessage; + } + // @ts-expect-error override to customize send + send(data) { + if (typeof data === "string" || + data instanceof Blob || + data instanceof ArrayBuffer || + ArrayBuffer.isView(data)) { + // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom + // parameterizes BufferSource as ArrayBufferView, so the + // ArrayBufferLike-backed view from isView() needs widening on forward. + super.send(data); + } + else if (data !== undefined && data !== null) { + super.send(data.toString()); + } + } + // implementation (signature is not part of the public overload set, so it is + // widened to encompass the overloads above under strictFunctionTypes) + addEventListener(type, listener, options) { + if (type === "message") { + const wrapped = ((ev) => { + let parsed = ev.data; + if (__classPrivateFieldGet(this, _WebSocketX_factoryCls, "f")) { + try { + parsed = new (__classPrivateFieldGet(this, _WebSocketX_factoryCls, "f"))(ev.data); + } + catch { + // if constructor rejects (e.g. ArrayBuffer not supported), keep raw + } + } + listener.call(this, new MessageEvent("message", { data: parsed })); + }); + super.addEventListener(type, wrapped, options); + } + else { + super.addEventListener(type, listener, options); + } + } +} +_WebSocketX_factoryCls = new WeakMap(); diff --git a/examples/in-browser-server/browser/gen/sdk/common/isPlausibleObject.js b/examples/in-browser-server/browser/gen/sdk/common/isPlausibleObject.js new file mode 100644 index 00000000..7425d176 --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/common/isPlausibleObject.js @@ -0,0 +1,12 @@ +export const isPlausibleObject = (obj) => { + const isBuffer = typeof globalThis.Buffer !== "undefined" && + typeof globalThis.Buffer.isBuffer === "function" && + globalThis.Buffer.isBuffer(obj); + const isBlob = typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob; + return (obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob); +}; diff --git a/examples/in-browser-server/browser/gen/sdk/common/operators.js b/examples/in-browser-server/browser/gen/sdk/common/operators.js index 57b1d36f..a1feab5e 100644 --- a/examples/in-browser-server/browser/gen/sdk/common/operators.js +++ b/examples/in-browser-server/browser/gen/sdk/common/operators.js @@ -6,6 +6,20 @@ export class MOne { isNull() { return this.content === null; } + static cast(value) { + if (typeof value === "object" && (value === null || value === void 0 ? void 0 : value.__operation)) { + const res = MOne.of(value === null || value === void 0 ? void 0 : value.content); + res.operation = value === null || value === void 0 ? void 0 : value.__operation; + return { + ok: true, + value: res, + }; + } + return { + value: null, + ok: false, + }; + } isSelector() { return this.selector !== undefined && this.operation !== null; } @@ -35,10 +49,6 @@ export class MOne { return this.content; } } -// In javascript, nullability and undefined is already working perfectly fine. -// hence, maybe just giving back one is enough. -export class MOneNullable extends MOne { -} // Array describes how an incoming list should be applied to an existing one, // mirroring emigo.Array on the Go side. It lets a PATCH-style payload say // "replace the whole set" versus "append to the existing set". @@ -51,6 +61,20 @@ export class MArray { this.operation = "replace"; this.items = []; } + static cast(value) { + if (typeof value === "object" && (value === null || value === void 0 ? void 0 : value.__operation)) { + const res = MArray.of(value === null || value === void 0 ? void 0 : value.items); + res.operation = value === null || value === void 0 ? void 0 : value.__operation; + return { + ok: true, + value: res, + }; + } + return { + value: null, + ok: false, + }; + } isAppend() { return this.operation === "append"; } @@ -89,10 +113,6 @@ export class MArray { return this.items; } } -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Array is enough. -export class MArrayNullable extends Array { -} // Collection mirrors emigo.Collection on the Go side. Structurally it is the // same as Array — a list carrying a "replace"/"append" operation — but it is a // distinct field type: a collection holds a list of a target entity, whereas an @@ -105,6 +125,20 @@ export class MCollection { isAppend() { return this.operation === "append"; } + static cast(value) { + if (typeof value === "object" && (value === null || value === void 0 ? void 0 : value.__operation)) { + const res = MCollection.of(value === null || value === void 0 ? void 0 : value.items); + res.operation = value === null || value === void 0 ? void 0 : value.__operation; + return { + ok: true, + value: res, + }; + } + return { + value: null, + ok: false, + }; + } isReplace() { return this.operation === "replace"; } @@ -140,7 +174,3 @@ export class MCollection { return this.items; } } -// In javascript, nullability and undefined is already working perfectly fine. -// hence, just extending Collection is enough. -export class MCollectionNullable extends MCollection { -} diff --git a/examples/in-browser-server/browser/gen/sdk/js/is-plausible-object.js b/examples/in-browser-server/browser/gen/sdk/js/is-plausible-object.js new file mode 100644 index 00000000..18d427b7 --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/js/is-plausible-object.js @@ -0,0 +1,19 @@ +/** + * Used in fetch context, to detect if the response is not a buffer + * or arraybufer, then create class instance of it. + * In such cases when response is blob, its better to pass the original classes to caller. + * @param obj + * @returns + */ +export const isPlausibleObject = (obj) => { + const isBuffer = typeof globalThis.Buffer !== "undefined" && + typeof globalThis.Buffer.isBuffer === "function" && + globalThis.Buffer.isBuffer(obj); + const isBlob = typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob; + return (obj && + typeof obj === "object" && + !Array.isArray(obj) && + !isBuffer && + !(obj instanceof ArrayBuffer) && + !isBlob); +}; diff --git a/examples/in-browser-server/browser/gen/sdk/react/useFetchx.js b/examples/in-browser-server/browser/gen/sdk/react/useFetchx.js new file mode 100644 index 00000000..0110e9d9 --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/react/useFetchx.js @@ -0,0 +1,6 @@ +import { createContext, useContext } from "react"; +const FetchxContextReact = createContext(null); +export const FetchxProvider = FetchxContextReact.Provider; +export function useFetchxContext() { + return useContext(FetchxContextReact); +} diff --git a/examples/in-browser-server/browser/gen/sdk/react/useSse.js b/examples/in-browser-server/browser/gen/sdk/react/useSse.js new file mode 100644 index 00000000..6245befe --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/react/useSse.js @@ -0,0 +1,33 @@ +import { useEffect, useRef, useState } from "react"; +export function useSse(fetchFn, props) { + const acRef = useRef(null); + const [state, setState] = useState({ + messages: [], + }); + const create = () => { + const ac = new AbortController(); + acRef.current = ac; + setState({ messages: [], error: null }); // reset on new stream + fetchFn((ev) => { + setState((value) => { + const next = ev.data; + if ((value.messages || []).includes(next)) + return value; + return { ...value, messages: [...(value.messages || []), next] }; + }); + }, props === null || props === void 0 ? void 0 : props.qs, { ...((props === null || props === void 0 ? void 0 : props.init) || {}), signal: ac.signal }, props === null || props === void 0 ? void 0 : props.overrideUrl).catch((err) => setState((v) => ({ ...v, error: err }))); + return () => { var _a; return (_a = acRef.current) === null || _a === void 0 ? void 0 : _a.abort(); }; + }; + useEffect(() => { + return create(); + }, []); + const cancel = () => { + var _a; + (_a = acRef.current) === null || _a === void 0 ? void 0 : _a.abort(); + }; + const restart = () => { + cancel(); + create(); + }; + return { ...state, cancel, restart, messages: state.messages }; +} diff --git a/examples/in-browser-server/browser/gen/sdk/react/useWebSocketX.js b/examples/in-browser-server/browser/gen/sdk/react/useWebSocketX.js new file mode 100644 index 00000000..66ae3c80 --- /dev/null +++ b/examples/in-browser-server/browser/gen/sdk/react/useWebSocketX.js @@ -0,0 +1,74 @@ +import { useEffect, useRef, useState, useCallback } from "react"; +export function useWebSocketX(fn) { + const socketRef = useRef(null); + const [state, setState] = useState({ + messages: [], + isOpen: false, + error: undefined, + }); + const create = useCallback(() => { + const ws = fn(); + socketRef.current = ws; + setState({ + messages: [], + error: undefined, + isOpen: ws.readyState === ws.OPEN, + }); + ws.addEventListener("message", (ev) => { + setState((prev) => { + return { + ...prev, + messages: [...prev.messages, ev.data], + }; + }); + }); + ws.addEventListener("error", (ev) => { + setState((prev) => { + return { + ...prev, + error: ev, + }; + }); + }); + ws.addEventListener("open", () => { + setState((prev) => { + return { + ...prev, + isOpen: true, + }; + }); + }); + ws.addEventListener("close", () => { + setState((prev) => { + return { + ...prev, + isOpen: false, + }; + }); + }); + return ws; + }, []); + useEffect(() => { + const ws = create(); + return () => ws.close(); + }, [create]); + const send = (msg) => { + var _a; + (_a = socketRef.current) === null || _a === void 0 ? void 0 : _a.send(msg); + }; + const close = () => { + var _a; + (_a = socketRef.current) === null || _a === void 0 ? void 0 : _a.close(); + }; + const restart = () => { + close(); + create(); + }; + return { + ...state, + send, + close, + restart, + socket: socketRef.current || undefined, + }; +} diff --git a/examples/in-browser-server/browser/index.html b/examples/in-browser-server/browser/index.html index 58df12fa..1e1fd825 100644 --- a/examples/in-browser-server/browser/index.html +++ b/examples/in-browser-server/browser/index.html @@ -47,6 +47,27 @@

Query users — GET /users


 
+    
+ +

Reactive chat — new WebSocketWasm("ws://chat/chat")

+

+ A real Go reactive handler running in wasm. The native-looking + WebSocketWasm echoes back the length of whatever you send. +

+
+ + + closed +
+
+ + +
+

+
     
     
   
diff --git a/examples/in-browser-server/browser/main.js b/examples/in-browser-server/browser/main.js
index cd11f6e5..5ef3fd49 100644
--- a/examples/in-browser-server/browser/main.js
+++ b/examples/in-browser-server/browser/main.js
@@ -1,4 +1,6 @@
 import "./database-bridge.js";
+import { WebSocketWasm } from "./WebSocketWasm.js";
+import { ChatAction } from "./gen/ChatAction.js";
 
 import { SubstringAction, SubstringActionRes } from "./gen/SubstringAction.js";
 console.log(1, SubstringAction);
@@ -126,3 +128,51 @@ $("deleteUser").addEventListener("click", async () => {
 });
 
 $("listUsers").addEventListener("click", refreshUsers);
+
+// --- Reactive chat over WebSocketWasm ------------------------------------
+// Note how this block uses the WebSocket API verbatim. Replace WebSocketWasm
+// with the native WebSocket (and point at a real ws:// server) and it behaves
+// identically.
+let chat = null;
+
+function setChatState(label, connected) {
+  $("chatState").textContent = label;
+  $("chatConnect").disabled = connected;
+  $("chatDisconnect").disabled = !connected;
+  $("chatSend").disabled = !connected;
+}
+
+function chatLog(line) {
+  $("chatOut").textContent += line + "\n";
+}
+
+$("chatConnect").addEventListener("click", () => {
+  chatLog("connecting…");
+  // Drive the GENERATED SDK client (ChatAction) — but tell it to use our
+  // WebSocketWasm transport instead of the browser's native WebSocket. Drop the
+  // SocketClass option and it would hit a real ws:// server unchanged.
+  chat = ChatAction.Create(undefined, undefined, {
+    SocketClass: WebSocketWasm,
+  });
+
+  chat.onopen = () => {
+    chatLog("● open");
+    setChatState("open", true);
+  };
+  chat.onmessage = (e) => chatLog("← " + e.data);
+  chat.onerror = (e) => chatLog("✕ error: " + (e.message || "unknown"));
+  chat.onclose = (e) => {
+    chatLog("○ close" + (e.reason ? " (" + e.reason + ")" : ""));
+    setChatState("closed", false);
+    chat = null;
+  };
+});
+
+$("chatSend").addEventListener("click", () => {
+  if (!chat) return;
+  const text = $("chatInput").value;
+  chat.send(text);
+  chatLog("→ " + text);
+});
+
+$("chatDisconnect").addEventListener("click", () => chat?.close());
diff --git a/examples/in-browser-server/cmd/server/main.go b/examples/in-browser-server/cmd/server/main.go
index a2a2291f..94c22399 100644
--- a/examples/in-browser-server/cmd/server/main.go
+++ b/examples/in-browser-server/cmd/server/main.go
@@ -12,8 +12,23 @@ func main() {
 
 	g := gin.Default()
 
+	// We need to actually connect to posgres.
+	// var conn internal.Database
+
+	// // User CRUD module shares the same connection. Make sure its table exists
+	// // before any request can land.
+	// users := &internal.UserModule{DB: conn}
+	// if err := users.EnsureSchema(context.Background()); err != nil {
+	// 	log.Fatalf("ensure users schema: %v", err)
+	// }
+
 	// Using implementation from internal package for gin
 	defs.SubstringActionGin(g, internal.SubstringAction)
+	// defs.CreateUserActionGin(g, users.Create)
+	// defs.ListUsersActionGin(g, users.List)
+	// defs.DeleteUserActionGin(g, users.Delete)
+
+	defs.ChatActionGin(g, internal.ChatHandler)
 
 	g.Run(":9123")
 }
diff --git a/examples/in-browser-server/cmd/wasm/main.go b/examples/in-browser-server/cmd/wasm/main.go
index 6e982fe6..7015cd17 100644
--- a/examples/in-browser-server/cmd/wasm/main.go
+++ b/examples/in-browser-server/cmd/wasm/main.go
@@ -44,6 +44,14 @@ func main() {
 
 	emigo.LiftWasmServer(mux, nil)
 
+	// Reactive (websocket-style) endpoints go through a separate bridge: the
+	// gorilla/gin path can't run in wasm (no hijackable socket), so the reactor
+	// talks the session's channels straight to the WebSocketWasm JS class. The
+	// ChatHandler factory is shared verbatim with the real gin server.
+	reactor := emigo.NewWasmReactor()
+	defs.ChatActionReactiveHandlerWasm(reactor, internal.ChatHandler)
+	reactor.Lift()
+
 	// Keep the Go runtime alive so the exposed callback stays callable.
 	select {}
 }
diff --git a/examples/in-browser-server/go.mod b/examples/in-browser-server/go.mod
index 69ca5d10..85b7d76a 100644
--- a/examples/in-browser-server/go.mod
+++ b/examples/in-browser-server/go.mod
@@ -4,6 +4,7 @@ go 1.26.1
 
 require (
 	github.com/gin-gonic/gin v1.12.0
+	github.com/gorilla/websocket v1.5.3
 	github.com/jackc/pgx/v5 v5.9.2
 	github.com/torabian/emi v1.2.1
 )
diff --git a/examples/in-browser-server/go.sum b/examples/in-browser-server/go.sum
index f07f3489..78392e8d 100644
--- a/examples/in-browser-server/go.sum
+++ b/examples/in-browser-server/go.sum
@@ -36,6 +36,8 @@ github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7Lk
 github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
 github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
 github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
 github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
 github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
 github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
diff --git a/examples/in-browser-server/in-browser-server.emi.yml b/examples/in-browser-server/in-browser-server.emi.yml
index 333c7e23..d01461fb 100644
--- a/examples/in-browser-server/in-browser-server.emi.yml
+++ b/examples/in-browser-server/in-browser-server.emi.yml
@@ -1,4 +1,9 @@
 actions:
+  - name: chat
+    url: /chat
+    description: A Reactive chating application, that returns length of strings you've typed.
+    method: reactive
+    
   - name: substring
     url: /
     method: post
diff --git a/examples/in-browser-server/internal/ChatActionImpl.go b/examples/in-browser-server/internal/ChatActionImpl.go
new file mode 100644
index 00000000..7b47dcba
--- /dev/null
+++ b/examples/in-browser-server/internal/ChatActionImpl.go
@@ -0,0 +1,36 @@
+package internal
+
+// This file is the manual, actual implementation of the reactive ChatAction.
+// Like SubstringActionImpl, it is transport-agnostic: the very same factory is
+// wired into the gin server (via defs.ChatActionReactiveHandler) and into the
+// wasm build (via defs.ChatActionReactiveHandlerWasm).
+
+import (
+	"fmt"
+
+	"github.com/torabian/emi/examples/in-browser-server/internal/defs"
+)
+
+// ChatHandler echoes back the length of every message the client types. It
+// returns the write channel the transport drains; closing that channel (here on
+// session.Done) initiates a clean close.
+func ChatHandler(session defs.ChatActionSession) (chan []byte, error) {
+	out := make(chan []byte, 16)
+
+	go func() {
+		defer close(out)
+		for {
+			select {
+			case msg := <-session.Read:
+				if msg.Error != nil {
+					return
+				}
+				out <- []byte(fmt.Sprintf("you typed %d chars: %q", len(msg.Data), string(msg.Data)))
+			case <-session.Done:
+				return
+			}
+		}
+	}()
+
+	return out, nil
+}
diff --git a/examples/in-browser-server/internal/defs/ChatAction.go b/examples/in-browser-server/internal/defs/ChatAction.go
new file mode 100644
index 00000000..d9730468
--- /dev/null
+++ b/examples/in-browser-server/internal/defs/ChatAction.go
@@ -0,0 +1,116 @@
+package defs
+
+import (
+	"github.com/torabian/emi/emigo"
+	"net/http"
+	"net/url"
+)
+
+/**
+* Action to communicate with the action ChatAction
+ */
+func ChatActionMeta() struct {
+	Name        string
+	URL         string
+	Method      string
+	CliName     string
+	Description string
+} {
+	return struct {
+		Name        string
+		URL         string
+		Method      string
+		CliName     string
+		Description string
+	}{
+		Name:        "ChatAction",
+		URL:         "/chat",
+		Method:      "REACTIVE",
+		CliName:     "",
+		Description: "A Reactive chating application, that returns length of strings you've typed.",
+	}
+}
+
+/**
+ * Query parameters for ChatAction
+ */
+// Query wrapper with private fields
+type ChatActionQuery struct {
+	values url.Values
+	mapped map[string]interface{}
+	// Typesafe fields
+}
+
+func ChatActionQueryFromString(rawQuery string) ChatActionQuery {
+	v := ChatActionQuery{}
+	values, _ := url.ParseQuery(rawQuery)
+	mapped := map[string]interface{}{}
+	if result, err := emigo.UnmarshalQs(rawQuery); err == nil {
+		mapped = result
+	}
+	decoder, err := emigo.NewDecoder(&emigo.DecoderConfig{
+		TagName:          "json", // reuse json tags
+		WeaklyTypedInput: true,   // "1" -> int, "true" -> bool
+		Result:           &v,
+	})
+	if err == nil {
+		_ = decoder.Decode(mapped)
+	}
+	v.values = values
+	v.mapped = mapped
+	return v
+}
+func ChatActionQueryFromHttp(r *http.Request) ChatActionQuery {
+	return ChatActionQueryFromString(r.URL.RawQuery)
+}
+func (q ChatActionQuery) Values() url.Values {
+	return q.values
+}
+func (q ChatActionQuery) Mapped() map[string]interface{} {
+	return q.mapped
+}
+func (q *ChatActionQuery) SetValues(v url.Values) {
+	q.values = v
+}
+func (q *ChatActionQuery) SetMapped(m map[string]interface{}) {
+	q.mapped = m
+}
+
+type ChatActionMessage struct {
+	Raw []byte
+	// Conn *websocket.Conn
+	Conn        interface{}
+	MessageType int
+	Error       error
+}
+
+// Developer handler type
+type ChatActionHandler func(msg ChatActionMessage) error
+type ChatActionSession struct {
+	// Ctx    *gin.Context
+	// Socket *websocket.Conn
+	Ctx         interface{}
+	Socket      interface{}
+	Done        chan bool
+	Read        chan ChatActionReadChan
+	QueryParams ChatActionQuery
+}
+type ChatActionHandlerDuplex func(*ChatActionSession)
+type ChatActionReadChan struct {
+	Data        []byte
+	Error       error
+	MessageType int
+}
+
+// ChatActionClientSession is the client-side mirror of
+// ChatActionSession. Receive frames on Read, send frames on Write,
+// and close Write (or send on Done) to tear the connection down. Done also
+// fires when the server closes or the socket errors, so the caller can use it
+// as a single disconnect signal.
+type ChatActionClientSession struct {
+	// Socket *websocket.Conn
+	Socket interface{}
+	Done   chan bool
+	Read   chan ChatActionReadChan
+	Write  chan []byte
+}
diff --git a/examples/in-browser-server/internal/defs/ChatActionGin.go b/examples/in-browser-server/internal/defs/ChatActionGin.go
new file mode 100644
index 00000000..adacf33e
--- /dev/null
+++ b/examples/in-browser-server/internal/defs/ChatActionGin.go
@@ -0,0 +1,238 @@
+//go:build !wasm
+
+package defs
+
+import (
+	"crypto/tls"
+	"github.com/gin-gonic/gin"
+	"github.com/gorilla/websocket"
+	"net/http"
+	"net/url"
+	"unicode/utf8"
+)
+
+/**
+* Action to communicate with the action ChatAction
+ */
+// WebSocket upgrader
+var upgraderChatAction = websocket.Upgrader{
+	CheckOrigin: func(r *http.Request) bool { return true },
+}
+
+func (x *ChatActionMessage) Connection() *websocket.Conn {
+	return x.Conn.(*websocket.Conn)
+}
+func (x *ChatActionClientSession) Connection() *websocket.Conn {
+	return x.Socket.(*websocket.Conn)
+}
+func (x *ChatActionSession) GinCtx() *gin.Context {
+	return x.Ctx.(*gin.Context)
+}
+
+// Generated handler
+func ChatActionGin(r *gin.Engine, factory func(
+	session ChatActionSession,
+) (chan []byte, error)) {
+	meta := ChatActionMeta()
+	r.GET(meta.URL, ChatActionReactiveHandler(factory))
+}
+func ChatActionReactiveHandler(factory func(
+	session ChatActionSession,
+) (chan []byte, error)) gin.HandlerFunc {
+	return func(ctx *gin.Context) {
+		read := make(chan ChatActionReadChan)
+		done := make(chan bool)
+		c, err := upgraderChatAction.Upgrade(ctx.Writer, ctx.Request, nil)
+		if err != nil {
+			c.WriteMessage(websocket.TextMessage, []byte(err.Error()))
+			c.Close()
+			return
+		}
+		session := ChatActionSession{
+			Ctx:    ctx,
+			Socket: c,
+			Done:   done,
+			Read:   read,
+		}
+		session.QueryParams = ChatActionQueryFromHttp(ctx.Request)
+		write, err := factory(session)
+		if err != nil {
+			c.WriteMessage(websocket.TextMessage, []byte(err.Error()))
+		}
+		go func() {
+			for {
+				_, data, err := c.ReadMessage()
+				read <- ChatActionReadChan{
+					Data:  data,
+					Error: err,
+				}
+				if err != nil {
+					return
+				}
+			}
+		}()
+		go func() {
+			for {
+				select {
+				case msg, ok := <-write:
+					if !ok {
+						// Channel closed; shutdown
+						c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+						done <- true
+						return
+					}
+					msgType := websocket.TextMessage
+					if !utf8.Valid(msg) {
+						msgType = websocket.BinaryMessage
+					}
+					err := c.WriteMessage(msgType, msg)
+					if err != nil {
+						// Optionally log the error or send to a logger
+						done <- true
+						return
+					}
+				case <-done:
+					c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+					return
+				}
+			}
+		}()
+	}
+}
+
+// ChatActionClientOptions configures a client dial. All fields are
+// optional — pass a zero value for a plaintext, header-less ws:// connection.
+//
+// TLSConfig governs the TLS handshake when dialing wss://. Set Certificates
+// and RootCAs (and optionally ServerName) for mTLS; leave nil for ws://.
+type ChatActionClientOptions struct {
+	Query     url.Values
+	TLSConfig *tls.Config
+	Headers   http.Header
+}
+
+// ChatActionClient dials the ChatAction endpoint at baseURL
+// (e.g. "ws://localhost:8080" or "https://host" — http/https are auto-rewritten
+// to ws/wss) and returns a session whose channels behave like the server's.
+//
+// Connect, then read and write concurrently. The Read goroutine bails on
+// msg.Error (server closed, network drop, etc.); the Done channel fires once
+// for any disconnect — use it to unblock main or trigger reconnect logic.
+//
+// For mTLS, build a *tls.Config with the client keypair + server CA and pass
+// it via opts.TLSConfig. The handshake completes before the websocket upgrade
+// is sent, so a bad cert fails this call rather than later on Read/Write.
+//
+//	sess, err := ChatActionClient(
+//	    "wss://hub.example.com",
+//	    ChatActionClientOptions{TLSConfig: tlsCfg},
+//	)
+//	if err != nil {
+//	    log.Fatal(err)
+//	}
+//
+//	// Reader: pull frames off sess.Read until error.
+//	go func() {
+//	    for {
+//	        msg := <-sess.Read
+//	        if msg.Error != nil {
+//	            log.Println("read error:", msg.Error)
+//	            return
+//	        }
+//	        log.Printf("server sent %d bytes: %s", len(msg.Data), msg.Data)
+//	    }
+//	}()
+//
+//	// Writer: send frames whenever you have something to say. Bytes that
+//	// aren't valid UTF-8 are sent as binary frames automatically.
+//	sess.Write <- []byte("hello server")
+//
+//	// Block until the connection drops, then exit. Alternatively, close
+//	// sess.Write to initiate a clean shutdown from the client side:
+//	//   close(sess.Write)
+//	<-sess.Done
+func ChatActionClient(baseURL string, opts *ChatActionClientOptions) (*ChatActionClientSession, error) {
+	u, err := url.Parse(baseURL)
+	if err != nil {
+		return nil, err
+	}
+	switch u.Scheme {
+	case "http":
+		u.Scheme = "ws"
+	case "https":
+		u.Scheme = "wss"
+	}
+	u.Path = ChatActionMeta().URL
+	if opts != nil && opts.Query != nil {
+		u.RawQuery = opts.Query.Encode()
+	}
+	var headers http.Header
+	if opts != nil {
+		headers = opts.Headers
+	}
+	dialer := &websocket.Dialer{}
+	if opts != nil {
+		dialer.TLSClientConfig = opts.TLSConfig
+	}
+	c, _, err := dialer.Dial(u.String(), headers)
+	if err != nil {
+		return nil, err
+	}
+	session := &ChatActionClientSession{
+		Socket: c,
+		Done:   make(chan bool, 1),
+		Read:   make(chan ChatActionReadChan),
+		Write:  make(chan []byte, 16),
+	}
+	// Reader goroutine: pumps frames from the socket into Read. On error it
+	// forwards the error frame, signals Done, and exits.
+	go func() {
+		for {
+			_, data, err := c.ReadMessage()
+			session.Read <- ChatActionReadChan{
+				Data:  data,
+				Error: err,
+			}
+			if err != nil {
+				select {
+				case session.Done <- true:
+				default:
+				}
+				return
+			}
+		}
+	}()
+	// Writer goroutine: drains Write to the socket. Closing Write triggers a
+	// clean close handshake; an error or Done signal closes the socket.
+	go func() {
+		defer c.Close()
+		for {
+			select {
+			case msg, ok := <-session.Write:
+				if !ok {
+					c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+					select {
+					case session.Done <- true:
+					default:
+					}
+					return
+				}
+				msgType := websocket.TextMessage
+				if !utf8.Valid(msg) {
+					msgType = websocket.BinaryMessage
+				}
+				if err := c.WriteMessage(msgType, msg); err != nil {
+					select {
+					case session.Done <- true:
+					default:
+					}
+					return
+				}
+			case <-session.Done:
+				c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+				return
+			}
+		}
+	}()
+	return session, nil
+}
diff --git a/examples/in-browser-server/internal/defs/ChatActionWasm.go b/examples/in-browser-server/internal/defs/ChatActionWasm.go
new file mode 100644
index 00000000..caec29f8
--- /dev/null
+++ b/examples/in-browser-server/internal/defs/ChatActionWasm.go
@@ -0,0 +1,62 @@
+//go:build wasm
+
+package defs
+
+import "github.com/torabian/emi/emigo"
+
+// ChatActionReactiveHandlerWasm is the in-browser counterpart of
+// ChatActionReactiveHandler. It registers the same developer factory against an
+// emigo.WasmReactor instead of a gin engine, so the business logic is shared
+// verbatim across the real server and the wasm build.
+//
+// There is no gorilla, no gin, and no socket here: the reactor bridges the
+// session's channels straight to the WebSocketWasm JS class.
+//
+func ChatActionReactiveHandlerWasm(
+	reactor *emigo.WasmReactor,
+	factory func(session ChatActionSession) (chan []byte, error),
+) {
+	reactor.Handle(ChatActionMeta().URL, func(conn *emigo.WasmReactiveConn) error {
+		session := ChatActionSession{
+			Done:        conn.Done,
+			Read:        make(chan ChatActionReadChan),
+			QueryParams: ChatActionQueryFromString(conn.Query.Encode()),
+			// Socket and Ctx stay nil — meaningless in the browser.
+		}
+		// client -> server: adapt raw []byte frames into the typed read channel.
+		go func() {
+			for {
+				select {
+				case data, ok := <-conn.Read:
+					if !ok {
+						return
+					}
+					session.Read <- ChatActionReadChan{Data: data}
+				case <-conn.Done:
+					return
+				}
+			}
+		}()
+		write, err := factory(session)
+		if err != nil {
+			return err
+		}
+		// server -> client: forward the factory's write channel to the bridge.
+		// Closing write signals a server-initiated close to the reactor.
+		go func() {
+			for {
+				select {
+				case msg, ok := <-write:
+					if !ok {
+						close(conn.Write)
+						return
+					}
+					conn.Write <- msg
+				case <-conn.Done:
+					return
+				}
+			}
+		}()
+		return nil
+	})
+}
diff --git a/examples/js-sdk-kit/build/common/WebSocketWasm.js b/examples/js-sdk-kit/build/common/WebSocketWasm.js
new file mode 100644
index 00000000..e8cb215e
--- /dev/null
+++ b/examples/js-sdk-kit/build/common/WebSocketWasm.js
@@ -0,0 +1,95 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+export class WebSocketWasm extends EventTarget {
+    constructor(url, _protocols) {
+        super();
+        this.url = url;
+        this.readyState = WebSocketWasm.CONNECTING;
+        this.onopen = null;
+        this.onmessage = null;
+        this.onerror = null;
+        this.onclose = null;
+        this._id = -1;
+        const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+        const path = u.pathname;
+        const query = u.search.replace(/^\?/, "");
+        // Defer so listeners attached right after `new` still catch 'open', exactly
+        // like the native async connect.
+        queueMicrotask(() => this._open(path, query));
+    }
+    _open(path, query) {
+        var _a;
+        const onMessage = (data) => {
+            var _a;
+            const ev = new MessageEvent("message", { data });
+            (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, ev);
+            this.dispatchEvent(ev);
+        };
+        const onClose = (reason) => {
+            var _a;
+            if (this.readyState === WebSocketWasm.CLOSED)
+                return;
+            this.readyState = WebSocketWasm.CLOSED;
+            const ev = new CloseEvent("close", {
+                reason,
+                code: 1000,
+                wasClean: true,
+            });
+            (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this, ev);
+            this.dispatchEvent(ev);
+        };
+        if (typeof window.wasmWsOpen !== "function") {
+            return this._fail("reactor not ready (window.wasmWsOpen missing)");
+        }
+        this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+        if (this._id < 0) {
+            return this._fail(`no reactive handler registered for "${path}"`);
+        }
+        this.readyState = WebSocketWasm.OPEN;
+        const ev = new Event("open");
+        (_a = this.onopen) === null || _a === void 0 ? void 0 : _a.call(this, ev);
+        this.dispatchEvent(ev);
+    }
+    _fail(message) {
+        var _a, _b;
+        this.readyState = WebSocketWasm.CLOSED;
+        const err = new Event("error");
+        err.message = message;
+        (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err);
+        this.dispatchEvent(err);
+        const close = new CloseEvent("close", {
+            reason: message,
+            code: 1006,
+            wasClean: false,
+        });
+        (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this, close);
+        this.dispatchEvent(close);
+    }
+    send(data) {
+        if (this.readyState !== WebSocketWasm.OPEN) {
+            throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+        }
+        // Strings pass through; everything else is stringified for now. Real binary
+        // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+        window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+    }
+    close(_code, _reason) {
+        if (this.readyState === WebSocketWasm.CLOSING ||
+            this.readyState === WebSocketWasm.CLOSED) {
+            return;
+        }
+        this.readyState = WebSocketWasm.CLOSING;
+        if (this._id >= 0)
+            window.wasmWsClose(this._id);
+    }
+}
+WebSocketWasm.CONNECTING = 0;
+WebSocketWasm.OPEN = 1;
+WebSocketWasm.CLOSING = 2;
+WebSocketWasm.CLOSED = 3;
diff --git a/examples/js-sdk-kit/build/common/WebSocketX.js b/examples/js-sdk-kit/build/common/WebSocketX.js
index f3601233..3dd0a7d4 100644
--- a/examples/js-sdk-kit/build/common/WebSocketX.js
+++ b/examples/js-sdk-kit/build/common/WebSocketX.js
@@ -37,13 +37,17 @@ export class WebSocketX extends WebSocket {
             data instanceof Blob ||
             data instanceof ArrayBuffer ||
             ArrayBuffer.isView(data)) {
+            // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+            // parameterizes BufferSource as ArrayBufferView, so the
+            // ArrayBufferLike-backed view from isView() needs widening on forward.
             super.send(data);
         }
         else if (data !== undefined && data !== null) {
             super.send(data.toString());
         }
     }
-    // implementation
+    // implementation (signature is not part of the public overload set, so it is
+    // widened to encompass the overloads above under strictFunctionTypes)
     addEventListener(type, listener, options) {
         if (type === "message") {
             const wrapped = ((ev) => {
diff --git a/examples/js-sdk-kit/src/common/WebSocketWasm.ts b/examples/js-sdk-kit/src/common/WebSocketWasm.ts
new file mode 100644
index 00000000..b4b63e1e
--- /dev/null
+++ b/examples/js-sdk-kit/src/common/WebSocketWasm.ts
@@ -0,0 +1,125 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+
+// The Go-WASM reactor installs these globals on `window`. Declare them so the
+// bridge calls below type-check.
+declare global {
+  interface Window {
+    wasmWsOpen?: (
+      path: string,
+      query: string,
+      onMessage: (data: string) => void,
+      onClose: (reason: string) => void,
+    ) => number;
+    wasmWsSend: (id: number, data: string) => void;
+    wasmWsClose: (id: number) => void;
+  }
+}
+
+export class WebSocketWasm extends EventTarget {
+  static readonly CONNECTING = 0;
+  static readonly OPEN = 1;
+  static readonly CLOSING = 2;
+  static readonly CLOSED = 3;
+
+  url: string;
+  readyState: number;
+  onopen: ((ev: Event) => void) | null;
+  onmessage: ((ev: MessageEvent) => void) | null;
+  onerror: ((ev: Event) => void) | null;
+  onclose: ((ev: CloseEvent) => void) | null;
+  private _id: number;
+
+  constructor(url: string, _protocols?: string | string[]) {
+    super();
+    this.url = url;
+    this.readyState = WebSocketWasm.CONNECTING;
+    this.onopen = null;
+    this.onmessage = null;
+    this.onerror = null;
+    this.onclose = null;
+    this._id = -1;
+
+    const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+    const path = u.pathname;
+    const query = u.search.replace(/^\?/, "");
+
+    // Defer so listeners attached right after `new` still catch 'open', exactly
+    // like the native async connect.
+    queueMicrotask(() => this._open(path, query));
+  }
+
+  private _open(path: string, query: string): void {
+    const onMessage = (data: string): void => {
+      const ev = new MessageEvent("message", { data });
+      this.onmessage?.(ev);
+      this.dispatchEvent(ev);
+    };
+    const onClose = (reason: string): void => {
+      if (this.readyState === WebSocketWasm.CLOSED) return;
+      this.readyState = WebSocketWasm.CLOSED;
+      const ev = new CloseEvent("close", {
+        reason,
+        code: 1000,
+        wasClean: true,
+      });
+      this.onclose?.(ev);
+      this.dispatchEvent(ev);
+    };
+
+    if (typeof window.wasmWsOpen !== "function") {
+      return this._fail("reactor not ready (window.wasmWsOpen missing)");
+    }
+
+    this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+    if (this._id < 0) {
+      return this._fail(`no reactive handler registered for "${path}"`);
+    }
+
+    this.readyState = WebSocketWasm.OPEN;
+    const ev = new Event("open");
+    this.onopen?.(ev);
+    this.dispatchEvent(ev);
+  }
+
+  private _fail(message: string): void {
+    this.readyState = WebSocketWasm.CLOSED;
+    const err: Event & { message?: string } = new Event("error");
+    err.message = message;
+    this.onerror?.(err);
+    this.dispatchEvent(err);
+    const close = new CloseEvent("close", {
+      reason: message,
+      code: 1006,
+      wasClean: false,
+    });
+    this.onclose?.(close);
+    this.dispatchEvent(close);
+  }
+
+  send(data: unknown): void {
+    if (this.readyState !== WebSocketWasm.OPEN) {
+      throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+    }
+    // Strings pass through; everything else is stringified for now. Real binary
+    // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+    window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+  }
+
+  close(_code?: number, _reason?: string): void {
+    if (
+      this.readyState === WebSocketWasm.CLOSING ||
+      this.readyState === WebSocketWasm.CLOSED
+    ) {
+      return;
+    }
+    this.readyState = WebSocketWasm.CLOSING;
+    if (this._id >= 0) window.wasmWsClose(this._id);
+  }
+}
diff --git a/examples/js-sdk-kit/src/common/WebSocketX.ts b/examples/js-sdk-kit/src/common/WebSocketX.ts
index cb1d758f..a8fdf3d9 100644
--- a/examples/js-sdk-kit/src/common/WebSocketX.ts
+++ b/examples/js-sdk-kit/src/common/WebSocketX.ts
@@ -47,7 +47,10 @@ export class WebSocketX<
       data instanceof ArrayBuffer ||
       ArrayBuffer.isView(data)
     ) {
-      super.send(data);
+      // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+      // parameterizes BufferSource as ArrayBufferView, so the
+      // ArrayBufferLike-backed view from isView() needs widening on forward.
+      super.send(data as Parameters[0]);
     } else if (data !== undefined && data !== null) {
       super.send(data.toString());
     }
@@ -66,10 +69,11 @@ export class WebSocketX<
     options?: boolean | AddEventListenerOptions
   ): void;
 
-  // implementation
+  // implementation (signature is not part of the public overload set, so it is
+  // widened to encompass the overloads above under strictFunctionTypes)
   addEventListener(
     type: string,
-    listener: EventListenerOrEventListenerObject,
+    listener: EventListenerOrEventListenerObject | ((this: WebSocket, ev: any) => unknown),
     options?: boolean | AddEventListenerOptions
   ): void {
     if (type === "message") {
diff --git a/examples/js-test/reactclient/src/generated/WebSocketOrgEchoAction.ts b/examples/js-test/reactclient/src/generated/WebSocketOrgEchoAction.ts
index c00b01b5..981a8dae 100644
--- a/examples/js-test/reactclient/src/generated/WebSocketOrgEchoAction.ts
+++ b/examples/js-test/reactclient/src/generated/WebSocketOrgEchoAction.ts
@@ -28,15 +28,14 @@ export class WebSocketOrgEchoAction {
   static NewUrl = (qs?: URLSearchParams) =>
     buildUrl(WebSocketOrgEchoAction.URL, undefined, qs);
   static Method = "reactive";
-  static Create = (overrideUrl?: string, qs?: URLSearchParams) => {
+  static Create = (overrideUrl?: string, qs?: URLSearchParams, options) => {
     const url = overrideUrl ?? WebSocketOrgEchoAction.NewUrl(qs);
-    return new WebSocketX(
-      url,
-      undefined,
-      {
-        MessageFactoryClass: WebSocketOrgEchoActionRes,
-      },
-    );
+    const Cls = options?.SocketClass
+      ? options.SocketClass
+      : WebSocketX;
+    return new Cls(url, undefined, {
+      MessageFactoryClass: WebSocketOrgEchoActionRes,
+    });
   };
   static Definition = {
     name: "webSocketOrgEcho",
diff --git a/examples/js-test/reactclient/src/generated/sdk/common/URLSearchParamsX.ts b/examples/js-test/reactclient/src/generated/sdk/common/URLSearchParamsX.ts
new file mode 100644
index 00000000..df1f8e4e
--- /dev/null
+++ b/examples/js-test/reactclient/src/generated/sdk/common/URLSearchParamsX.ts
@@ -0,0 +1,144 @@
+import { stringify, parse } from "qs";
+
+/**
+ * Extended URLSearchParams that stores data in a nested object
+ * and keeps compatibility with URLSearchParams methods.
+ */
+export class URLSearchParamsX extends URLSearchParams {
+  /** Internal data store */
+  private data: Record = {};
+
+  constructor(
+    init?: string[][] | Record | string | URLSearchParams
+  ) {
+    super(init);
+    if (init) {
+      if (typeof init === "string") {
+        Object.assign(this.data, parse(init));
+      } else if (init instanceof URLSearchParams) {
+        Object.assign(this.data, parse(init.toString()));
+      } else if (Array.isArray(init)) {
+        init.forEach(([k, v]) => (this.data[k] = v));
+      } else {
+        Object.assign(this.data, init);
+      }
+    }
+  }
+
+  /** Remove a key from the store */
+  override delete(name: string): void {
+    delete this.data[name];
+  }
+
+  /** Append a value to an array or create a new array */
+  override append(name: string, value: string): void {
+    if (this.data[name] === undefined) this.data[name] = value;
+    else if (Array.isArray(this.data[name])) this.data[name].push(value);
+    else this.data[name] = [this.data[name], value];
+  }
+
+  /** Get an iterator of top-level keys */
+  override keys(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        yield key;
+      }
+      return undefined;
+    })();
+  }
+
+  /** Number of top-level keys */
+  override get size(): number {
+    return Object.keys(this.data).length;
+  }
+
+  /** Sort top-level keys */
+  override sort(): void {
+    const sorted: Record = {};
+    Object.keys(this.data)
+      .sort()
+      .forEach((key) => {
+        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+        sorted[key] = this.data[key];
+      });
+    this.data = sorted;
+  }
+
+  /** Get an iterator of top-level values */
+  override values(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        const val = obj[key];
+        // Make sure val is string
+        yield String(val);
+      }
+      return undefined;
+    })();
+  }
+
+  /** Get a single value by key */
+  override get(name: string): string | null {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val == null) return null;
+    return Array.isArray(val) ? String(val[0]) : String(val);
+  }
+
+  /** Check if key exists */
+  override has(name: string): boolean {
+    return this.data[name] !== undefined;
+  }
+
+  /** Iterate over top-level keys and values */
+  override forEach(
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    callbackfn: (value: any, key: string, parent: any) => void
+  ): void {
+    for (const key of Object.keys(this.data)) {
+      callbackfn(this.data[key], key, this);
+    }
+  }
+
+  /** Get all values for a key as array */
+  override getAll(name: string): string[] {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val === undefined) return [];
+    return Array.isArray(val) ? val.map(String) : [String(val)];
+  }
+
+  /** Get an iterator of key/value pairs (flattened) */
+  override entries() {
+    const params = new URLSearchParams(stringify(this.data));
+    return params.entries();
+  }
+
+  /** Convert to query string */
+  override toString(): string {
+    return stringify(this.data);
+  }
+
+  /** Set a key to a value */
+  override set(name: string, value: any): this {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    this.data[name] = value;
+    return this;
+  }
+
+  /** Convert entries to plain object */
+  toObject(): Record {
+    return Object.fromEntries(this.entries());
+  }
+
+  // eslint-disable-next-line no-unused-private-class-members
+  protected getTyped(key: string, type: string) {
+    const val = this.get(key);
+    if (val == null) return null;
+    const t = type.toLowerCase();
+    if (t.includes("number")) return Number(val);
+    if (t.includes("bool")) return val === "true";
+    return val;
+  }
+}
diff --git a/examples/js-test/reactclient/src/generated/sdk/common/WebSocketWasm.ts b/examples/js-test/reactclient/src/generated/sdk/common/WebSocketWasm.ts
new file mode 100644
index 00000000..b4b63e1e
--- /dev/null
+++ b/examples/js-test/reactclient/src/generated/sdk/common/WebSocketWasm.ts
@@ -0,0 +1,125 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+
+// The Go-WASM reactor installs these globals on `window`. Declare them so the
+// bridge calls below type-check.
+declare global {
+  interface Window {
+    wasmWsOpen?: (
+      path: string,
+      query: string,
+      onMessage: (data: string) => void,
+      onClose: (reason: string) => void,
+    ) => number;
+    wasmWsSend: (id: number, data: string) => void;
+    wasmWsClose: (id: number) => void;
+  }
+}
+
+export class WebSocketWasm extends EventTarget {
+  static readonly CONNECTING = 0;
+  static readonly OPEN = 1;
+  static readonly CLOSING = 2;
+  static readonly CLOSED = 3;
+
+  url: string;
+  readyState: number;
+  onopen: ((ev: Event) => void) | null;
+  onmessage: ((ev: MessageEvent) => void) | null;
+  onerror: ((ev: Event) => void) | null;
+  onclose: ((ev: CloseEvent) => void) | null;
+  private _id: number;
+
+  constructor(url: string, _protocols?: string | string[]) {
+    super();
+    this.url = url;
+    this.readyState = WebSocketWasm.CONNECTING;
+    this.onopen = null;
+    this.onmessage = null;
+    this.onerror = null;
+    this.onclose = null;
+    this._id = -1;
+
+    const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+    const path = u.pathname;
+    const query = u.search.replace(/^\?/, "");
+
+    // Defer so listeners attached right after `new` still catch 'open', exactly
+    // like the native async connect.
+    queueMicrotask(() => this._open(path, query));
+  }
+
+  private _open(path: string, query: string): void {
+    const onMessage = (data: string): void => {
+      const ev = new MessageEvent("message", { data });
+      this.onmessage?.(ev);
+      this.dispatchEvent(ev);
+    };
+    const onClose = (reason: string): void => {
+      if (this.readyState === WebSocketWasm.CLOSED) return;
+      this.readyState = WebSocketWasm.CLOSED;
+      const ev = new CloseEvent("close", {
+        reason,
+        code: 1000,
+        wasClean: true,
+      });
+      this.onclose?.(ev);
+      this.dispatchEvent(ev);
+    };
+
+    if (typeof window.wasmWsOpen !== "function") {
+      return this._fail("reactor not ready (window.wasmWsOpen missing)");
+    }
+
+    this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+    if (this._id < 0) {
+      return this._fail(`no reactive handler registered for "${path}"`);
+    }
+
+    this.readyState = WebSocketWasm.OPEN;
+    const ev = new Event("open");
+    this.onopen?.(ev);
+    this.dispatchEvent(ev);
+  }
+
+  private _fail(message: string): void {
+    this.readyState = WebSocketWasm.CLOSED;
+    const err: Event & { message?: string } = new Event("error");
+    err.message = message;
+    this.onerror?.(err);
+    this.dispatchEvent(err);
+    const close = new CloseEvent("close", {
+      reason: message,
+      code: 1006,
+      wasClean: false,
+    });
+    this.onclose?.(close);
+    this.dispatchEvent(close);
+  }
+
+  send(data: unknown): void {
+    if (this.readyState !== WebSocketWasm.OPEN) {
+      throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+    }
+    // Strings pass through; everything else is stringified for now. Real binary
+    // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+    window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+  }
+
+  close(_code?: number, _reason?: string): void {
+    if (
+      this.readyState === WebSocketWasm.CLOSING ||
+      this.readyState === WebSocketWasm.CLOSED
+    ) {
+      return;
+    }
+    this.readyState = WebSocketWasm.CLOSING;
+    if (this._id >= 0) window.wasmWsClose(this._id);
+  }
+}
diff --git a/examples/js-test/reactclient/src/generated/sdk/common/WebSocketX.ts b/examples/js-test/reactclient/src/generated/sdk/common/WebSocketX.ts
index cb1d758f..a8fdf3d9 100644
--- a/examples/js-test/reactclient/src/generated/sdk/common/WebSocketX.ts
+++ b/examples/js-test/reactclient/src/generated/sdk/common/WebSocketX.ts
@@ -47,7 +47,10 @@ export class WebSocketX<
       data instanceof ArrayBuffer ||
       ArrayBuffer.isView(data)
     ) {
-      super.send(data);
+      // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+      // parameterizes BufferSource as ArrayBufferView, so the
+      // ArrayBufferLike-backed view from isView() needs widening on forward.
+      super.send(data as Parameters[0]);
     } else if (data !== undefined && data !== null) {
       super.send(data.toString());
     }
@@ -66,10 +69,11 @@ export class WebSocketX<
     options?: boolean | AddEventListenerOptions
   ): void;
 
-  // implementation
+  // implementation (signature is not part of the public overload set, so it is
+  // widened to encompass the overloads above under strictFunctionTypes)
   addEventListener(
     type: string,
-    listener: EventListenerOrEventListenerObject,
+    listener: EventListenerOrEventListenerObject | ((this: WebSocket, ev: any) => unknown),
     options?: boolean | AddEventListenerOptions
   ): void {
     if (type === "message") {
diff --git a/examples/js-test/reactclient/src/generated/sdk/common/isPlausibleObject.ts b/examples/js-test/reactclient/src/generated/sdk/common/isPlausibleObject.ts
new file mode 100644
index 00000000..e3f57236
--- /dev/null
+++ b/examples/js-test/reactclient/src/generated/sdk/common/isPlausibleObject.ts
@@ -0,0 +1,18 @@
+export const isPlausibleObject = (obj: any) => {
+  const isBuffer =
+    typeof globalThis.Buffer !== "undefined" &&
+    typeof globalThis.Buffer.isBuffer === "function" &&
+    globalThis.Buffer.isBuffer(obj);
+
+  const isBlob =
+    typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob;
+
+  return (
+    obj &&
+    typeof obj === "object" &&
+    !Array.isArray(obj) &&
+    !isBuffer &&
+    !(obj instanceof ArrayBuffer) &&
+    !isBlob
+  );
+};
diff --git a/examples/js-test/reactclient/src/generated/sdk/js/is-plausible-object.ts b/examples/js-test/reactclient/src/generated/sdk/js/is-plausible-object.ts
new file mode 100644
index 00000000..2fc6200d
--- /dev/null
+++ b/examples/js-test/reactclient/src/generated/sdk/js/is-plausible-object.ts
@@ -0,0 +1,25 @@
+/**
+ * Used in fetch context, to detect if the response is not a buffer
+ * or arraybufer, then create class instance of it.
+ * In such cases when response is blob, its better to pass the original classes to caller.
+ * @param obj
+ * @returns
+ */
+export const isPlausibleObject = (obj: any) => {
+  const isBuffer =
+    typeof globalThis.Buffer !== "undefined" &&
+    typeof globalThis.Buffer.isBuffer === "function" &&
+    globalThis.Buffer.isBuffer(obj);
+
+  const isBlob =
+    typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob;
+
+  return (
+    obj &&
+    typeof obj === "object" &&
+    !Array.isArray(obj) &&
+    !isBuffer &&
+    !(obj instanceof ArrayBuffer) &&
+    !isBlob
+  );
+};
diff --git a/examples/js-test/reactclient/src/generated/sdk/react/useSse.ts b/examples/js-test/reactclient/src/generated/sdk/react/useSse.ts
new file mode 100644
index 00000000..576fddde
--- /dev/null
+++ b/examples/js-test/reactclient/src/generated/sdk/react/useSse.ts
@@ -0,0 +1,68 @@
+import { useEffect, useRef, useState } from "react";
+import type { TypedRequestInit } from "../common/fetchx";
+
+export interface UseSSEResult {
+  messages: Array;
+  error?: Error | null;
+  cancel: () => void;
+  restart: () => void;
+}
+
+type SseFetchFn = (
+  onMessage?: (ev: MessageEvent) => void,
+  qs?: Q,
+  init?: TypedRequestInit,
+  overrideUrl?: string
+) => Promise;
+
+export function useSse(
+  fetchFn: SseFetchFn,
+  props?: {
+    qs?: Q;
+    init?: TypedRequestInit;
+    overrideUrl?: string;
+  }
+) {
+  const acRef = useRef(null);
+
+  const [state, setState] = useState>>({
+    messages: [],
+  });
+
+  const create = () => {
+    const ac = new AbortController();
+    acRef.current = ac;
+
+    setState({ messages: [], error: null }); // reset on new stream
+
+    fetchFn(
+      (ev) => {
+        setState((value) => {
+          const next = ev.data as T;
+          if ((value.messages || []).includes(next)) return value;
+          return { ...value, messages: [...(value.messages || []), next] };
+        });
+      },
+      props?.qs,
+      { ...(props?.init || {}), signal: ac.signal },
+      props?.overrideUrl
+    ).catch((err) => setState((v) => ({ ...v, error: err as Error })));
+
+    return () => acRef.current?.abort();
+  };
+
+  useEffect(() => {
+    return create();
+  }, []);
+
+  const cancel = () => {
+    acRef.current?.abort();
+  };
+
+  const restart = () => {
+    cancel();
+    create();
+  };
+
+  return { ...state, cancel, restart, messages: state.messages as T[] };
+}
diff --git a/examples/js/test-artifacts/http-action-test-output/sdk/common/URLSearchParamsX.ts b/examples/js/test-artifacts/http-action-test-output/sdk/common/URLSearchParamsX.ts
new file mode 100644
index 00000000..6cd269cc
--- /dev/null
+++ b/examples/js/test-artifacts/http-action-test-output/sdk/common/URLSearchParamsX.ts
@@ -0,0 +1,144 @@
+import { stringify, parse } from "qs";
+
+/**
+ * Extended URLSearchParams that stores data in a nested object
+ * and keeps compatibility with URLSearchParams methods.
+ */
+export class URLSearchParamsX extends URLSearchParams {
+  /** Internal data store */
+  private data: Record = {};
+
+  constructor(
+    init?: string[][] | Record | string | URLSearchParams,
+  ) {
+    super(init);
+    if (init) {
+      if (typeof init === "string") {
+        Object.assign(this.data, parse(init));
+      } else if (init instanceof URLSearchParams) {
+        Object.assign(this.data, parse(init.toString()));
+      } else if (Array.isArray(init)) {
+        init.forEach(([k, v]) => (this.data[k] = v));
+      } else {
+        Object.assign(this.data, init);
+      }
+    }
+  }
+
+  /** Remove a key from the store */
+  override delete(name: string): void {
+    delete this.data[name];
+  }
+
+  /** Append a value to an array or create a new array */
+  override append(name: string, value: string): void {
+    if (this.data[name] === undefined) this.data[name] = value;
+    else if (Array.isArray(this.data[name])) this.data[name].push(value);
+    else this.data[name] = [this.data[name], value];
+  }
+
+  /** Get an iterator of top-level keys */
+  override keys(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        yield key;
+      }
+      return undefined;
+    })();
+  }
+
+  /** Number of top-level keys */
+  override get size(): number {
+    return Object.keys(this.data).length;
+  }
+
+  /** Sort top-level keys */
+  override sort(): void {
+    const sorted: Record = {};
+    Object.keys(this.data)
+      .sort()
+      .forEach((key) => {
+        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+        sorted[key] = this.data[key];
+      });
+    this.data = sorted;
+  }
+
+  /** Get an iterator of top-level values */
+  override values(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        const val = obj[key];
+        // Make sure val is string
+        yield String(val);
+      }
+      return undefined;
+    })();
+  }
+
+  /** Get a single value by key */
+  override get(name: string): string | null {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val == null) return null;
+    return Array.isArray(val) ? String(val[0]) : String(val);
+  }
+
+  /** Check if key exists */
+  override has(name: string): boolean {
+    return this.data[name] !== undefined;
+  }
+
+  /** Iterate over top-level keys and values */
+  override forEach(
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    callbackfn: (value: any, key: string, parent: any) => void,
+  ): void {
+    for (const key of Object.keys(this.data)) {
+      callbackfn(this.data[key], key, this);
+    }
+  }
+
+  /** Get all values for a key as array */
+  override getAll(name: string): string[] {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val === undefined) return [];
+    return Array.isArray(val) ? val.map(String) : [String(val)];
+  }
+
+  /** Get an iterator of key/value pairs (flattened) */
+  override entries() {
+    const params = new URLSearchParams(stringify(this.data));
+    return params.entries();
+  }
+
+  /** Convert to query string */
+  override toString(): string {
+    return stringify(this.data);
+  }
+
+  /** Set a key to a value */
+  override set(name: string, value: any): this {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    this.data[name] = value;
+    return this;
+  }
+
+  /** Convert entries to plain object */
+  toObject(): Record {
+    return Object.fromEntries(this.entries());
+  }
+
+  // eslint-disable-next-line no-unused-private-class-members
+  protected getTyped(key: string, type: string) {
+    const val = this.get(key);
+    if (val == null) return null;
+    const t = type.toLowerCase();
+    if (t.includes("number")) return Number(val);
+    if (t.includes("bool")) return val === "true";
+    return val;
+  }
+}
diff --git a/examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketWasm.ts b/examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketWasm.ts
new file mode 100644
index 00000000..b4b63e1e
--- /dev/null
+++ b/examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketWasm.ts
@@ -0,0 +1,125 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+
+// The Go-WASM reactor installs these globals on `window`. Declare them so the
+// bridge calls below type-check.
+declare global {
+  interface Window {
+    wasmWsOpen?: (
+      path: string,
+      query: string,
+      onMessage: (data: string) => void,
+      onClose: (reason: string) => void,
+    ) => number;
+    wasmWsSend: (id: number, data: string) => void;
+    wasmWsClose: (id: number) => void;
+  }
+}
+
+export class WebSocketWasm extends EventTarget {
+  static readonly CONNECTING = 0;
+  static readonly OPEN = 1;
+  static readonly CLOSING = 2;
+  static readonly CLOSED = 3;
+
+  url: string;
+  readyState: number;
+  onopen: ((ev: Event) => void) | null;
+  onmessage: ((ev: MessageEvent) => void) | null;
+  onerror: ((ev: Event) => void) | null;
+  onclose: ((ev: CloseEvent) => void) | null;
+  private _id: number;
+
+  constructor(url: string, _protocols?: string | string[]) {
+    super();
+    this.url = url;
+    this.readyState = WebSocketWasm.CONNECTING;
+    this.onopen = null;
+    this.onmessage = null;
+    this.onerror = null;
+    this.onclose = null;
+    this._id = -1;
+
+    const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+    const path = u.pathname;
+    const query = u.search.replace(/^\?/, "");
+
+    // Defer so listeners attached right after `new` still catch 'open', exactly
+    // like the native async connect.
+    queueMicrotask(() => this._open(path, query));
+  }
+
+  private _open(path: string, query: string): void {
+    const onMessage = (data: string): void => {
+      const ev = new MessageEvent("message", { data });
+      this.onmessage?.(ev);
+      this.dispatchEvent(ev);
+    };
+    const onClose = (reason: string): void => {
+      if (this.readyState === WebSocketWasm.CLOSED) return;
+      this.readyState = WebSocketWasm.CLOSED;
+      const ev = new CloseEvent("close", {
+        reason,
+        code: 1000,
+        wasClean: true,
+      });
+      this.onclose?.(ev);
+      this.dispatchEvent(ev);
+    };
+
+    if (typeof window.wasmWsOpen !== "function") {
+      return this._fail("reactor not ready (window.wasmWsOpen missing)");
+    }
+
+    this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+    if (this._id < 0) {
+      return this._fail(`no reactive handler registered for "${path}"`);
+    }
+
+    this.readyState = WebSocketWasm.OPEN;
+    const ev = new Event("open");
+    this.onopen?.(ev);
+    this.dispatchEvent(ev);
+  }
+
+  private _fail(message: string): void {
+    this.readyState = WebSocketWasm.CLOSED;
+    const err: Event & { message?: string } = new Event("error");
+    err.message = message;
+    this.onerror?.(err);
+    this.dispatchEvent(err);
+    const close = new CloseEvent("close", {
+      reason: message,
+      code: 1006,
+      wasClean: false,
+    });
+    this.onclose?.(close);
+    this.dispatchEvent(close);
+  }
+
+  send(data: unknown): void {
+    if (this.readyState !== WebSocketWasm.OPEN) {
+      throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+    }
+    // Strings pass through; everything else is stringified for now. Real binary
+    // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+    window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+  }
+
+  close(_code?: number, _reason?: string): void {
+    if (
+      this.readyState === WebSocketWasm.CLOSING ||
+      this.readyState === WebSocketWasm.CLOSED
+    ) {
+      return;
+    }
+    this.readyState = WebSocketWasm.CLOSING;
+    if (this._id >= 0) window.wasmWsClose(this._id);
+  }
+}
diff --git a/examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketX.ts b/examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketX.ts
new file mode 100644
index 00000000..9b0544f6
--- /dev/null
+++ b/examples/js/test-artifacts/http-action-test-output/sdk/common/WebSocketX.ts
@@ -0,0 +1,103 @@
+type ConstructorWithArg = new (arg: T, ...rest: any[]) => R;
+
+export class WebSocketX<
+  SendType = string | ArrayBufferLike | Blob | ArrayBufferView,
+  RecieveData = string,
+> extends WebSocket {
+  public readonly addEventListenerRaw: WebSocket["addEventListener"];
+  public readonly sendRaw: WebSocket["send"];
+  #factoryCls?: ConstructorWithArg;
+
+  constructor(
+    url: string | URL,
+    protocols?: string | string[],
+    options?: {
+      MessageFactoryClass?: ConstructorWithArg;
+    },
+  ) {
+    super(url, protocols);
+
+    this.sendRaw = super.send.bind(this);
+    this.addEventListenerRaw = super.addEventListener.bind(this);
+
+    if (options?.MessageFactoryClass) {
+      this.#factoryCls = options.MessageFactoryClass;
+    }
+  }
+
+  set onmessage(
+    fn: ((this: WebSocket, ev: MessageEvent) => any) | null,
+  ) {
+    if (fn) {
+      this.addEventListener("message", fn);
+    } else {
+      super.onmessage = null;
+    }
+  }
+
+  get onmessage() {
+    return super.onmessage;
+  }
+
+  // @ts-expect-error override to customize send
+  send(data: SendType): void {
+    if (
+      typeof data === "string" ||
+      data instanceof Blob ||
+      data instanceof ArrayBuffer ||
+      ArrayBuffer.isView(data)
+    ) {
+      // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+      // parameterizes BufferSource as ArrayBufferView, so the
+      // ArrayBufferLike-backed view from isView() needs widening on forward.
+      super.send(data as Parameters[0]);
+    } else if (data !== undefined && data !== null) {
+      super.send(data.toString());
+    }
+  }
+
+  addEventListener(
+    type: "message",
+    listener: (this: WebSocket, ev: MessageEvent) => unknown,
+    options?: boolean | AddEventListenerOptions,
+  ): void;
+
+  // fallback overloads (other event types)
+  addEventListener>(
+    type: K,
+    listener: (this: WebSocket, ev: WebSocketEventMap[K]) => unknown,
+    options?: boolean | AddEventListenerOptions,
+  ): void;
+
+  // implementation (signature is not part of the public overload set, so it is
+  // widened to encompass the overloads above under strictFunctionTypes)
+  addEventListener(
+    type: string,
+    listener:
+      | EventListenerOrEventListenerObject
+      | ((this: WebSocket, ev: any) => unknown),
+    options?: boolean | AddEventListenerOptions,
+  ): void {
+    if (type === "message") {
+      const wrapped = ((ev: MessageEvent) => {
+        let parsed: unknown = ev.data;
+        if (this.#factoryCls) {
+          try {
+            parsed = new this.#factoryCls(ev.data);
+          } catch {
+            // if constructor rejects (e.g. ArrayBuffer not supported), keep raw
+          }
+        }
+
+        (listener as EventListener).call(
+          this,
+          new MessageEvent("message", { data: parsed }),
+        );
+      }) as EventListener;
+
+      super.addEventListener(type, wrapped, options);
+    } else {
+      super.addEventListener(type, listener, options);
+    }
+  }
+}
diff --git a/examples/js/test-artifacts/http-action-test-output/sdk/js/is-plausible-object.ts b/examples/js/test-artifacts/http-action-test-output/sdk/js/is-plausible-object.ts
new file mode 100644
index 00000000..2fc6200d
--- /dev/null
+++ b/examples/js/test-artifacts/http-action-test-output/sdk/js/is-plausible-object.ts
@@ -0,0 +1,25 @@
+/**
+ * Used in fetch context, to detect if the response is not a buffer
+ * or arraybufer, then create class instance of it.
+ * In such cases when response is blob, its better to pass the original classes to caller.
+ * @param obj
+ * @returns
+ */
+export const isPlausibleObject = (obj: any) => {
+  const isBuffer =
+    typeof globalThis.Buffer !== "undefined" &&
+    typeof globalThis.Buffer.isBuffer === "function" &&
+    globalThis.Buffer.isBuffer(obj);
+
+  const isBlob =
+    typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob;
+
+  return (
+    obj &&
+    typeof obj === "object" &&
+    !Array.isArray(obj) &&
+    !isBuffer &&
+    !(obj instanceof ArrayBuffer) &&
+    !isBlob
+  );
+};
diff --git a/examples/js/test-artifacts/http-action-test-output/sdk/react/useFetchx.ts b/examples/js/test-artifacts/http-action-test-output/sdk/react/useFetchx.ts
new file mode 100644
index 00000000..58017a04
--- /dev/null
+++ b/examples/js/test-artifacts/http-action-test-output/sdk/react/useFetchx.ts
@@ -0,0 +1,10 @@
+import { createContext, useContext } from "react";
+import { FetchxContext } from "../common/fetchx";
+
+const FetchxContextReact = createContext(null);
+
+export const FetchxProvider = FetchxContextReact.Provider;
+
+export function useFetchxContext(): FetchxContext | null {
+  return useContext(FetchxContextReact);
+}
diff --git a/examples/js/test-artifacts/http-action-test-output/sdk/react/useSse.ts b/examples/js/test-artifacts/http-action-test-output/sdk/react/useSse.ts
new file mode 100644
index 00000000..3c13f623
--- /dev/null
+++ b/examples/js/test-artifacts/http-action-test-output/sdk/react/useSse.ts
@@ -0,0 +1,68 @@
+import { useEffect, useRef, useState } from "react";
+import type { TypedRequestInit } from "../common/fetchx";
+
+export interface UseSSEResult {
+  messages: Array;
+  error?: Error | null;
+  cancel: () => void;
+  restart: () => void;
+}
+
+type SseFetchFn = (
+  onMessage?: (ev: MessageEvent) => void,
+  qs?: Q,
+  init?: TypedRequestInit,
+  overrideUrl?: string,
+) => Promise;
+
+export function useSse(
+  fetchFn: SseFetchFn,
+  props?: {
+    qs?: Q;
+    init?: TypedRequestInit;
+    overrideUrl?: string;
+  },
+) {
+  const acRef = useRef(null);
+
+  const [state, setState] = useState>>({
+    messages: [],
+  });
+
+  const create = () => {
+    const ac = new AbortController();
+    acRef.current = ac;
+
+    setState({ messages: [], error: null }); // reset on new stream
+
+    fetchFn(
+      (ev) => {
+        setState((value) => {
+          const next = ev.data as T;
+          if ((value.messages || []).includes(next)) return value;
+          return { ...value, messages: [...(value.messages || []), next] };
+        });
+      },
+      props?.qs,
+      { ...(props?.init || {}), signal: ac.signal },
+      props?.overrideUrl,
+    ).catch((err) => setState((v) => ({ ...v, error: err as Error })));
+
+    return () => acRef.current?.abort();
+  };
+
+  useEffect(() => {
+    return create();
+  }, []);
+
+  const cancel = () => {
+    acRef.current?.abort();
+  };
+
+  const restart = () => {
+    cancel();
+    create();
+  };
+
+  return { ...state, cancel, restart, messages: state.messages as T[] };
+}
diff --git a/examples/js/test-artifacts/http-action-test-output/sdk/react/useWebSocketX.ts b/examples/js/test-artifacts/http-action-test-output/sdk/react/useWebSocketX.ts
new file mode 100644
index 00000000..8b8696a5
--- /dev/null
+++ b/examples/js/test-artifacts/http-action-test-output/sdk/react/useWebSocketX.ts
@@ -0,0 +1,104 @@
+import { useEffect, useRef, useState, useCallback } from "react";
+import { WebSocketX } from "../common/WebSocketX";
+
+export type UseWebSocketResult = {
+  send: (msg: TSend) => void;
+  close: () => void;
+  restart: () => void;
+  socket?: WebSocketX;
+} & UseWebSocketState;
+
+interface UseWebSocketState {
+  messages: TRecv[];
+  isOpen: boolean;
+  error?: Event | null;
+}
+
+export function useWebSocketX(
+  fn: (
+    overrideUrl?: string | undefined,
+    qs?: TQuery | undefined,
+  ) => WebSocketX,
+): UseWebSocketResult {
+  const socketRef = useRef | null>(null);
+  const [state, setState] = useState>({
+    messages: [],
+    isOpen: false,
+    error: undefined,
+  });
+
+  const create = useCallback(() => {
+    const ws = fn();
+    socketRef.current = ws;
+
+    setState({
+      messages: [],
+      error: undefined,
+      isOpen: ws.readyState === ws.OPEN,
+    });
+
+    ws.addEventListener("message", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          messages: [...prev.messages, ev.data],
+        };
+      });
+    });
+
+    ws.addEventListener("error", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          error: ev,
+        };
+      });
+    });
+
+    ws.addEventListener("open", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: true,
+        };
+      });
+    });
+
+    ws.addEventListener("close", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: false,
+        };
+      });
+    });
+
+    return ws;
+  }, []);
+
+  useEffect(() => {
+    const ws = create();
+    return () => ws.close();
+  }, [create]);
+
+  const send = (msg: TSend) => {
+    socketRef.current?.send(msg);
+  };
+
+  const close = () => {
+    socketRef.current?.close();
+  };
+
+  const restart = () => {
+    close();
+    create();
+  };
+
+  return {
+    ...state,
+    send,
+    close,
+    restart,
+    socket: socketRef.current || undefined,
+  };
+}
diff --git a/examples/js/test-artifacts/http-emi-react-output/sdk/common/URLSearchParamsX.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/common/URLSearchParamsX.ts
new file mode 100644
index 00000000..6cd269cc
--- /dev/null
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/common/URLSearchParamsX.ts
@@ -0,0 +1,144 @@
+import { stringify, parse } from "qs";
+
+/**
+ * Extended URLSearchParams that stores data in a nested object
+ * and keeps compatibility with URLSearchParams methods.
+ */
+export class URLSearchParamsX extends URLSearchParams {
+  /** Internal data store */
+  private data: Record = {};
+
+  constructor(
+    init?: string[][] | Record | string | URLSearchParams,
+  ) {
+    super(init);
+    if (init) {
+      if (typeof init === "string") {
+        Object.assign(this.data, parse(init));
+      } else if (init instanceof URLSearchParams) {
+        Object.assign(this.data, parse(init.toString()));
+      } else if (Array.isArray(init)) {
+        init.forEach(([k, v]) => (this.data[k] = v));
+      } else {
+        Object.assign(this.data, init);
+      }
+    }
+  }
+
+  /** Remove a key from the store */
+  override delete(name: string): void {
+    delete this.data[name];
+  }
+
+  /** Append a value to an array or create a new array */
+  override append(name: string, value: string): void {
+    if (this.data[name] === undefined) this.data[name] = value;
+    else if (Array.isArray(this.data[name])) this.data[name].push(value);
+    else this.data[name] = [this.data[name], value];
+  }
+
+  /** Get an iterator of top-level keys */
+  override keys(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        yield key;
+      }
+      return undefined;
+    })();
+  }
+
+  /** Number of top-level keys */
+  override get size(): number {
+    return Object.keys(this.data).length;
+  }
+
+  /** Sort top-level keys */
+  override sort(): void {
+    const sorted: Record = {};
+    Object.keys(this.data)
+      .sort()
+      .forEach((key) => {
+        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+        sorted[key] = this.data[key];
+      });
+    this.data = sorted;
+  }
+
+  /** Get an iterator of top-level values */
+  override values(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        const val = obj[key];
+        // Make sure val is string
+        yield String(val);
+      }
+      return undefined;
+    })();
+  }
+
+  /** Get a single value by key */
+  override get(name: string): string | null {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val == null) return null;
+    return Array.isArray(val) ? String(val[0]) : String(val);
+  }
+
+  /** Check if key exists */
+  override has(name: string): boolean {
+    return this.data[name] !== undefined;
+  }
+
+  /** Iterate over top-level keys and values */
+  override forEach(
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    callbackfn: (value: any, key: string, parent: any) => void,
+  ): void {
+    for (const key of Object.keys(this.data)) {
+      callbackfn(this.data[key], key, this);
+    }
+  }
+
+  /** Get all values for a key as array */
+  override getAll(name: string): string[] {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val === undefined) return [];
+    return Array.isArray(val) ? val.map(String) : [String(val)];
+  }
+
+  /** Get an iterator of key/value pairs (flattened) */
+  override entries() {
+    const params = new URLSearchParams(stringify(this.data));
+    return params.entries();
+  }
+
+  /** Convert to query string */
+  override toString(): string {
+    return stringify(this.data);
+  }
+
+  /** Set a key to a value */
+  override set(name: string, value: any): this {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    this.data[name] = value;
+    return this;
+  }
+
+  /** Convert entries to plain object */
+  toObject(): Record {
+    return Object.fromEntries(this.entries());
+  }
+
+  // eslint-disable-next-line no-unused-private-class-members
+  protected getTyped(key: string, type: string) {
+    const val = this.get(key);
+    if (val == null) return null;
+    const t = type.toLowerCase();
+    if (t.includes("number")) return Number(val);
+    if (t.includes("bool")) return val === "true";
+    return val;
+  }
+}
diff --git a/examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketWasm.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketWasm.ts
new file mode 100644
index 00000000..b4b63e1e
--- /dev/null
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketWasm.ts
@@ -0,0 +1,125 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+
+// The Go-WASM reactor installs these globals on `window`. Declare them so the
+// bridge calls below type-check.
+declare global {
+  interface Window {
+    wasmWsOpen?: (
+      path: string,
+      query: string,
+      onMessage: (data: string) => void,
+      onClose: (reason: string) => void,
+    ) => number;
+    wasmWsSend: (id: number, data: string) => void;
+    wasmWsClose: (id: number) => void;
+  }
+}
+
+export class WebSocketWasm extends EventTarget {
+  static readonly CONNECTING = 0;
+  static readonly OPEN = 1;
+  static readonly CLOSING = 2;
+  static readonly CLOSED = 3;
+
+  url: string;
+  readyState: number;
+  onopen: ((ev: Event) => void) | null;
+  onmessage: ((ev: MessageEvent) => void) | null;
+  onerror: ((ev: Event) => void) | null;
+  onclose: ((ev: CloseEvent) => void) | null;
+  private _id: number;
+
+  constructor(url: string, _protocols?: string | string[]) {
+    super();
+    this.url = url;
+    this.readyState = WebSocketWasm.CONNECTING;
+    this.onopen = null;
+    this.onmessage = null;
+    this.onerror = null;
+    this.onclose = null;
+    this._id = -1;
+
+    const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+    const path = u.pathname;
+    const query = u.search.replace(/^\?/, "");
+
+    // Defer so listeners attached right after `new` still catch 'open', exactly
+    // like the native async connect.
+    queueMicrotask(() => this._open(path, query));
+  }
+
+  private _open(path: string, query: string): void {
+    const onMessage = (data: string): void => {
+      const ev = new MessageEvent("message", { data });
+      this.onmessage?.(ev);
+      this.dispatchEvent(ev);
+    };
+    const onClose = (reason: string): void => {
+      if (this.readyState === WebSocketWasm.CLOSED) return;
+      this.readyState = WebSocketWasm.CLOSED;
+      const ev = new CloseEvent("close", {
+        reason,
+        code: 1000,
+        wasClean: true,
+      });
+      this.onclose?.(ev);
+      this.dispatchEvent(ev);
+    };
+
+    if (typeof window.wasmWsOpen !== "function") {
+      return this._fail("reactor not ready (window.wasmWsOpen missing)");
+    }
+
+    this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+    if (this._id < 0) {
+      return this._fail(`no reactive handler registered for "${path}"`);
+    }
+
+    this.readyState = WebSocketWasm.OPEN;
+    const ev = new Event("open");
+    this.onopen?.(ev);
+    this.dispatchEvent(ev);
+  }
+
+  private _fail(message: string): void {
+    this.readyState = WebSocketWasm.CLOSED;
+    const err: Event & { message?: string } = new Event("error");
+    err.message = message;
+    this.onerror?.(err);
+    this.dispatchEvent(err);
+    const close = new CloseEvent("close", {
+      reason: message,
+      code: 1006,
+      wasClean: false,
+    });
+    this.onclose?.(close);
+    this.dispatchEvent(close);
+  }
+
+  send(data: unknown): void {
+    if (this.readyState !== WebSocketWasm.OPEN) {
+      throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+    }
+    // Strings pass through; everything else is stringified for now. Real binary
+    // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+    window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+  }
+
+  close(_code?: number, _reason?: string): void {
+    if (
+      this.readyState === WebSocketWasm.CLOSING ||
+      this.readyState === WebSocketWasm.CLOSED
+    ) {
+      return;
+    }
+    this.readyState = WebSocketWasm.CLOSING;
+    if (this._id >= 0) window.wasmWsClose(this._id);
+  }
+}
diff --git a/examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketX.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketX.ts
new file mode 100644
index 00000000..9b0544f6
--- /dev/null
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/common/WebSocketX.ts
@@ -0,0 +1,103 @@
+type ConstructorWithArg = new (arg: T, ...rest: any[]) => R;
+
+export class WebSocketX<
+  SendType = string | ArrayBufferLike | Blob | ArrayBufferView,
+  RecieveData = string,
+> extends WebSocket {
+  public readonly addEventListenerRaw: WebSocket["addEventListener"];
+  public readonly sendRaw: WebSocket["send"];
+  #factoryCls?: ConstructorWithArg;
+
+  constructor(
+    url: string | URL,
+    protocols?: string | string[],
+    options?: {
+      MessageFactoryClass?: ConstructorWithArg;
+    },
+  ) {
+    super(url, protocols);
+
+    this.sendRaw = super.send.bind(this);
+    this.addEventListenerRaw = super.addEventListener.bind(this);
+
+    if (options?.MessageFactoryClass) {
+      this.#factoryCls = options.MessageFactoryClass;
+    }
+  }
+
+  set onmessage(
+    fn: ((this: WebSocket, ev: MessageEvent) => any) | null,
+  ) {
+    if (fn) {
+      this.addEventListener("message", fn);
+    } else {
+      super.onmessage = null;
+    }
+  }
+
+  get onmessage() {
+    return super.onmessage;
+  }
+
+  // @ts-expect-error override to customize send
+  send(data: SendType): void {
+    if (
+      typeof data === "string" ||
+      data instanceof Blob ||
+      data instanceof ArrayBuffer ||
+      ArrayBuffer.isView(data)
+    ) {
+      // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+      // parameterizes BufferSource as ArrayBufferView, so the
+      // ArrayBufferLike-backed view from isView() needs widening on forward.
+      super.send(data as Parameters[0]);
+    } else if (data !== undefined && data !== null) {
+      super.send(data.toString());
+    }
+  }
+
+  addEventListener(
+    type: "message",
+    listener: (this: WebSocket, ev: MessageEvent) => unknown,
+    options?: boolean | AddEventListenerOptions,
+  ): void;
+
+  // fallback overloads (other event types)
+  addEventListener>(
+    type: K,
+    listener: (this: WebSocket, ev: WebSocketEventMap[K]) => unknown,
+    options?: boolean | AddEventListenerOptions,
+  ): void;
+
+  // implementation (signature is not part of the public overload set, so it is
+  // widened to encompass the overloads above under strictFunctionTypes)
+  addEventListener(
+    type: string,
+    listener:
+      | EventListenerOrEventListenerObject
+      | ((this: WebSocket, ev: any) => unknown),
+    options?: boolean | AddEventListenerOptions,
+  ): void {
+    if (type === "message") {
+      const wrapped = ((ev: MessageEvent) => {
+        let parsed: unknown = ev.data;
+        if (this.#factoryCls) {
+          try {
+            parsed = new this.#factoryCls(ev.data);
+          } catch {
+            // if constructor rejects (e.g. ArrayBuffer not supported), keep raw
+          }
+        }
+
+        (listener as EventListener).call(
+          this,
+          new MessageEvent("message", { data: parsed }),
+        );
+      }) as EventListener;
+
+      super.addEventListener(type, wrapped, options);
+    } else {
+      super.addEventListener(type, listener, options);
+    }
+  }
+}
diff --git a/examples/js/test-artifacts/http-emi-react-output/sdk/common/isPlausibleObject.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/common/isPlausibleObject.ts
new file mode 100644
index 00000000..e3f57236
--- /dev/null
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/common/isPlausibleObject.ts
@@ -0,0 +1,18 @@
+export const isPlausibleObject = (obj: any) => {
+  const isBuffer =
+    typeof globalThis.Buffer !== "undefined" &&
+    typeof globalThis.Buffer.isBuffer === "function" &&
+    globalThis.Buffer.isBuffer(obj);
+
+  const isBlob =
+    typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob;
+
+  return (
+    obj &&
+    typeof obj === "object" &&
+    !Array.isArray(obj) &&
+    !isBuffer &&
+    !(obj instanceof ArrayBuffer) &&
+    !isBlob
+  );
+};
diff --git a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/withPrefix.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/common/withPrefix.ts
similarity index 97%
rename from examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/withPrefix.ts
rename to examples/js/test-artifacts/http-emi-react-output/sdk/common/withPrefix.ts
index 8630562e..8b9f767e 100644
--- a/examples/allegro-sdk/javascript/gen/offer/offer-translations/sdk/common/withPrefix.ts
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/common/withPrefix.ts
@@ -1,6 +1,6 @@
 export function withPrefix>(
   prefix: string,
-  fields: T
+  fields: T,
 ): T {
   const out: Record = {};
   for (const [k, v] of Object.entries(fields)) {
diff --git a/examples/js/test-artifacts/http-emi-react-output/sdk/js/is-plausible-object.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/js/is-plausible-object.ts
new file mode 100644
index 00000000..2fc6200d
--- /dev/null
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/js/is-plausible-object.ts
@@ -0,0 +1,25 @@
+/**
+ * Used in fetch context, to detect if the response is not a buffer
+ * or arraybufer, then create class instance of it.
+ * In such cases when response is blob, its better to pass the original classes to caller.
+ * @param obj
+ * @returns
+ */
+export const isPlausibleObject = (obj: any) => {
+  const isBuffer =
+    typeof globalThis.Buffer !== "undefined" &&
+    typeof globalThis.Buffer.isBuffer === "function" &&
+    globalThis.Buffer.isBuffer(obj);
+
+  const isBlob =
+    typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob;
+
+  return (
+    obj &&
+    typeof obj === "object" &&
+    !Array.isArray(obj) &&
+    !isBuffer &&
+    !(obj instanceof ArrayBuffer) &&
+    !isBlob
+  );
+};
diff --git a/examples/js/test-artifacts/http-emi-react-output/sdk/react/useSse.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/react/useSse.ts
new file mode 100644
index 00000000..3c13f623
--- /dev/null
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/react/useSse.ts
@@ -0,0 +1,68 @@
+import { useEffect, useRef, useState } from "react";
+import type { TypedRequestInit } from "../common/fetchx";
+
+export interface UseSSEResult {
+  messages: Array;
+  error?: Error | null;
+  cancel: () => void;
+  restart: () => void;
+}
+
+type SseFetchFn = (
+  onMessage?: (ev: MessageEvent) => void,
+  qs?: Q,
+  init?: TypedRequestInit,
+  overrideUrl?: string,
+) => Promise;
+
+export function useSse(
+  fetchFn: SseFetchFn,
+  props?: {
+    qs?: Q;
+    init?: TypedRequestInit;
+    overrideUrl?: string;
+  },
+) {
+  const acRef = useRef(null);
+
+  const [state, setState] = useState>>({
+    messages: [],
+  });
+
+  const create = () => {
+    const ac = new AbortController();
+    acRef.current = ac;
+
+    setState({ messages: [], error: null }); // reset on new stream
+
+    fetchFn(
+      (ev) => {
+        setState((value) => {
+          const next = ev.data as T;
+          if ((value.messages || []).includes(next)) return value;
+          return { ...value, messages: [...(value.messages || []), next] };
+        });
+      },
+      props?.qs,
+      { ...(props?.init || {}), signal: ac.signal },
+      props?.overrideUrl,
+    ).catch((err) => setState((v) => ({ ...v, error: err as Error })));
+
+    return () => acRef.current?.abort();
+  };
+
+  useEffect(() => {
+    return create();
+  }, []);
+
+  const cancel = () => {
+    acRef.current?.abort();
+  };
+
+  const restart = () => {
+    cancel();
+    create();
+  };
+
+  return { ...state, cancel, restart, messages: state.messages as T[] };
+}
diff --git a/examples/js/test-artifacts/http-emi-react-output/sdk/react/useWebSocketX.ts b/examples/js/test-artifacts/http-emi-react-output/sdk/react/useWebSocketX.ts
new file mode 100644
index 00000000..8b8696a5
--- /dev/null
+++ b/examples/js/test-artifacts/http-emi-react-output/sdk/react/useWebSocketX.ts
@@ -0,0 +1,104 @@
+import { useEffect, useRef, useState, useCallback } from "react";
+import { WebSocketX } from "../common/WebSocketX";
+
+export type UseWebSocketResult = {
+  send: (msg: TSend) => void;
+  close: () => void;
+  restart: () => void;
+  socket?: WebSocketX;
+} & UseWebSocketState;
+
+interface UseWebSocketState {
+  messages: TRecv[];
+  isOpen: boolean;
+  error?: Event | null;
+}
+
+export function useWebSocketX(
+  fn: (
+    overrideUrl?: string | undefined,
+    qs?: TQuery | undefined,
+  ) => WebSocketX,
+): UseWebSocketResult {
+  const socketRef = useRef | null>(null);
+  const [state, setState] = useState>({
+    messages: [],
+    isOpen: false,
+    error: undefined,
+  });
+
+  const create = useCallback(() => {
+    const ws = fn();
+    socketRef.current = ws;
+
+    setState({
+      messages: [],
+      error: undefined,
+      isOpen: ws.readyState === ws.OPEN,
+    });
+
+    ws.addEventListener("message", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          messages: [...prev.messages, ev.data],
+        };
+      });
+    });
+
+    ws.addEventListener("error", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          error: ev,
+        };
+      });
+    });
+
+    ws.addEventListener("open", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: true,
+        };
+      });
+    });
+
+    ws.addEventListener("close", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: false,
+        };
+      });
+    });
+
+    return ws;
+  }, []);
+
+  useEffect(() => {
+    const ws = create();
+    return () => ws.close();
+  }, [create]);
+
+  const send = (msg: TSend) => {
+    socketRef.current?.send(msg);
+  };
+
+  const close = () => {
+    socketRef.current?.close();
+  };
+
+  const restart = () => {
+    close();
+    create();
+  };
+
+  return {
+    ...state,
+    send,
+    close,
+    restart,
+    socket: socketRef.current || undefined,
+  };
+}
diff --git a/examples/js/test-artifacts/http-envelop-test-output/sdk/common/URLSearchParamsX.ts b/examples/js/test-artifacts/http-envelop-test-output/sdk/common/URLSearchParamsX.ts
new file mode 100644
index 00000000..6cd269cc
--- /dev/null
+++ b/examples/js/test-artifacts/http-envelop-test-output/sdk/common/URLSearchParamsX.ts
@@ -0,0 +1,144 @@
+import { stringify, parse } from "qs";
+
+/**
+ * Extended URLSearchParams that stores data in a nested object
+ * and keeps compatibility with URLSearchParams methods.
+ */
+export class URLSearchParamsX extends URLSearchParams {
+  /** Internal data store */
+  private data: Record = {};
+
+  constructor(
+    init?: string[][] | Record | string | URLSearchParams,
+  ) {
+    super(init);
+    if (init) {
+      if (typeof init === "string") {
+        Object.assign(this.data, parse(init));
+      } else if (init instanceof URLSearchParams) {
+        Object.assign(this.data, parse(init.toString()));
+      } else if (Array.isArray(init)) {
+        init.forEach(([k, v]) => (this.data[k] = v));
+      } else {
+        Object.assign(this.data, init);
+      }
+    }
+  }
+
+  /** Remove a key from the store */
+  override delete(name: string): void {
+    delete this.data[name];
+  }
+
+  /** Append a value to an array or create a new array */
+  override append(name: string, value: string): void {
+    if (this.data[name] === undefined) this.data[name] = value;
+    else if (Array.isArray(this.data[name])) this.data[name].push(value);
+    else this.data[name] = [this.data[name], value];
+  }
+
+  /** Get an iterator of top-level keys */
+  override keys(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        yield key;
+      }
+      return undefined;
+    })();
+  }
+
+  /** Number of top-level keys */
+  override get size(): number {
+    return Object.keys(this.data).length;
+  }
+
+  /** Sort top-level keys */
+  override sort(): void {
+    const sorted: Record = {};
+    Object.keys(this.data)
+      .sort()
+      .forEach((key) => {
+        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+        sorted[key] = this.data[key];
+      });
+    this.data = sorted;
+  }
+
+  /** Get an iterator of top-level values */
+  override values(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        const val = obj[key];
+        // Make sure val is string
+        yield String(val);
+      }
+      return undefined;
+    })();
+  }
+
+  /** Get a single value by key */
+  override get(name: string): string | null {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val == null) return null;
+    return Array.isArray(val) ? String(val[0]) : String(val);
+  }
+
+  /** Check if key exists */
+  override has(name: string): boolean {
+    return this.data[name] !== undefined;
+  }
+
+  /** Iterate over top-level keys and values */
+  override forEach(
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    callbackfn: (value: any, key: string, parent: any) => void,
+  ): void {
+    for (const key of Object.keys(this.data)) {
+      callbackfn(this.data[key], key, this);
+    }
+  }
+
+  /** Get all values for a key as array */
+  override getAll(name: string): string[] {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val === undefined) return [];
+    return Array.isArray(val) ? val.map(String) : [String(val)];
+  }
+
+  /** Get an iterator of key/value pairs (flattened) */
+  override entries() {
+    const params = new URLSearchParams(stringify(this.data));
+    return params.entries();
+  }
+
+  /** Convert to query string */
+  override toString(): string {
+    return stringify(this.data);
+  }
+
+  /** Set a key to a value */
+  override set(name: string, value: any): this {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    this.data[name] = value;
+    return this;
+  }
+
+  /** Convert entries to plain object */
+  toObject(): Record {
+    return Object.fromEntries(this.entries());
+  }
+
+  // eslint-disable-next-line no-unused-private-class-members
+  protected getTyped(key: string, type: string) {
+    const val = this.get(key);
+    if (val == null) return null;
+    const t = type.toLowerCase();
+    if (t.includes("number")) return Number(val);
+    if (t.includes("bool")) return val === "true";
+    return val;
+  }
+}
diff --git a/examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketWasm.ts b/examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketWasm.ts
new file mode 100644
index 00000000..b4b63e1e
--- /dev/null
+++ b/examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketWasm.ts
@@ -0,0 +1,125 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+
+// The Go-WASM reactor installs these globals on `window`. Declare them so the
+// bridge calls below type-check.
+declare global {
+  interface Window {
+    wasmWsOpen?: (
+      path: string,
+      query: string,
+      onMessage: (data: string) => void,
+      onClose: (reason: string) => void,
+    ) => number;
+    wasmWsSend: (id: number, data: string) => void;
+    wasmWsClose: (id: number) => void;
+  }
+}
+
+export class WebSocketWasm extends EventTarget {
+  static readonly CONNECTING = 0;
+  static readonly OPEN = 1;
+  static readonly CLOSING = 2;
+  static readonly CLOSED = 3;
+
+  url: string;
+  readyState: number;
+  onopen: ((ev: Event) => void) | null;
+  onmessage: ((ev: MessageEvent) => void) | null;
+  onerror: ((ev: Event) => void) | null;
+  onclose: ((ev: CloseEvent) => void) | null;
+  private _id: number;
+
+  constructor(url: string, _protocols?: string | string[]) {
+    super();
+    this.url = url;
+    this.readyState = WebSocketWasm.CONNECTING;
+    this.onopen = null;
+    this.onmessage = null;
+    this.onerror = null;
+    this.onclose = null;
+    this._id = -1;
+
+    const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+    const path = u.pathname;
+    const query = u.search.replace(/^\?/, "");
+
+    // Defer so listeners attached right after `new` still catch 'open', exactly
+    // like the native async connect.
+    queueMicrotask(() => this._open(path, query));
+  }
+
+  private _open(path: string, query: string): void {
+    const onMessage = (data: string): void => {
+      const ev = new MessageEvent("message", { data });
+      this.onmessage?.(ev);
+      this.dispatchEvent(ev);
+    };
+    const onClose = (reason: string): void => {
+      if (this.readyState === WebSocketWasm.CLOSED) return;
+      this.readyState = WebSocketWasm.CLOSED;
+      const ev = new CloseEvent("close", {
+        reason,
+        code: 1000,
+        wasClean: true,
+      });
+      this.onclose?.(ev);
+      this.dispatchEvent(ev);
+    };
+
+    if (typeof window.wasmWsOpen !== "function") {
+      return this._fail("reactor not ready (window.wasmWsOpen missing)");
+    }
+
+    this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+    if (this._id < 0) {
+      return this._fail(`no reactive handler registered for "${path}"`);
+    }
+
+    this.readyState = WebSocketWasm.OPEN;
+    const ev = new Event("open");
+    this.onopen?.(ev);
+    this.dispatchEvent(ev);
+  }
+
+  private _fail(message: string): void {
+    this.readyState = WebSocketWasm.CLOSED;
+    const err: Event & { message?: string } = new Event("error");
+    err.message = message;
+    this.onerror?.(err);
+    this.dispatchEvent(err);
+    const close = new CloseEvent("close", {
+      reason: message,
+      code: 1006,
+      wasClean: false,
+    });
+    this.onclose?.(close);
+    this.dispatchEvent(close);
+  }
+
+  send(data: unknown): void {
+    if (this.readyState !== WebSocketWasm.OPEN) {
+      throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+    }
+    // Strings pass through; everything else is stringified for now. Real binary
+    // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+    window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+  }
+
+  close(_code?: number, _reason?: string): void {
+    if (
+      this.readyState === WebSocketWasm.CLOSING ||
+      this.readyState === WebSocketWasm.CLOSED
+    ) {
+      return;
+    }
+    this.readyState = WebSocketWasm.CLOSING;
+    if (this._id >= 0) window.wasmWsClose(this._id);
+  }
+}
diff --git a/examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketX.ts b/examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketX.ts
new file mode 100644
index 00000000..9b0544f6
--- /dev/null
+++ b/examples/js/test-artifacts/http-envelop-test-output/sdk/common/WebSocketX.ts
@@ -0,0 +1,103 @@
+type ConstructorWithArg = new (arg: T, ...rest: any[]) => R;
+
+export class WebSocketX<
+  SendType = string | ArrayBufferLike | Blob | ArrayBufferView,
+  RecieveData = string,
+> extends WebSocket {
+  public readonly addEventListenerRaw: WebSocket["addEventListener"];
+  public readonly sendRaw: WebSocket["send"];
+  #factoryCls?: ConstructorWithArg;
+
+  constructor(
+    url: string | URL,
+    protocols?: string | string[],
+    options?: {
+      MessageFactoryClass?: ConstructorWithArg;
+    },
+  ) {
+    super(url, protocols);
+
+    this.sendRaw = super.send.bind(this);
+    this.addEventListenerRaw = super.addEventListener.bind(this);
+
+    if (options?.MessageFactoryClass) {
+      this.#factoryCls = options.MessageFactoryClass;
+    }
+  }
+
+  set onmessage(
+    fn: ((this: WebSocket, ev: MessageEvent) => any) | null,
+  ) {
+    if (fn) {
+      this.addEventListener("message", fn);
+    } else {
+      super.onmessage = null;
+    }
+  }
+
+  get onmessage() {
+    return super.onmessage;
+  }
+
+  // @ts-expect-error override to customize send
+  send(data: SendType): void {
+    if (
+      typeof data === "string" ||
+      data instanceof Blob ||
+      data instanceof ArrayBuffer ||
+      ArrayBuffer.isView(data)
+    ) {
+      // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+      // parameterizes BufferSource as ArrayBufferView, so the
+      // ArrayBufferLike-backed view from isView() needs widening on forward.
+      super.send(data as Parameters[0]);
+    } else if (data !== undefined && data !== null) {
+      super.send(data.toString());
+    }
+  }
+
+  addEventListener(
+    type: "message",
+    listener: (this: WebSocket, ev: MessageEvent) => unknown,
+    options?: boolean | AddEventListenerOptions,
+  ): void;
+
+  // fallback overloads (other event types)
+  addEventListener>(
+    type: K,
+    listener: (this: WebSocket, ev: WebSocketEventMap[K]) => unknown,
+    options?: boolean | AddEventListenerOptions,
+  ): void;
+
+  // implementation (signature is not part of the public overload set, so it is
+  // widened to encompass the overloads above under strictFunctionTypes)
+  addEventListener(
+    type: string,
+    listener:
+      | EventListenerOrEventListenerObject
+      | ((this: WebSocket, ev: any) => unknown),
+    options?: boolean | AddEventListenerOptions,
+  ): void {
+    if (type === "message") {
+      const wrapped = ((ev: MessageEvent) => {
+        let parsed: unknown = ev.data;
+        if (this.#factoryCls) {
+          try {
+            parsed = new this.#factoryCls(ev.data);
+          } catch {
+            // if constructor rejects (e.g. ArrayBuffer not supported), keep raw
+          }
+        }
+
+        (listener as EventListener).call(
+          this,
+          new MessageEvent("message", { data: parsed }),
+        );
+      }) as EventListener;
+
+      super.addEventListener(type, wrapped, options);
+    } else {
+      super.addEventListener(type, listener, options);
+    }
+  }
+}
diff --git a/examples/js/test-artifacts/http-envelop-test-output/sdk/js/is-plausible-object.ts b/examples/js/test-artifacts/http-envelop-test-output/sdk/js/is-plausible-object.ts
new file mode 100644
index 00000000..2fc6200d
--- /dev/null
+++ b/examples/js/test-artifacts/http-envelop-test-output/sdk/js/is-plausible-object.ts
@@ -0,0 +1,25 @@
+/**
+ * Used in fetch context, to detect if the response is not a buffer
+ * or arraybufer, then create class instance of it.
+ * In such cases when response is blob, its better to pass the original classes to caller.
+ * @param obj
+ * @returns
+ */
+export const isPlausibleObject = (obj: any) => {
+  const isBuffer =
+    typeof globalThis.Buffer !== "undefined" &&
+    typeof globalThis.Buffer.isBuffer === "function" &&
+    globalThis.Buffer.isBuffer(obj);
+
+  const isBlob =
+    typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob;
+
+  return (
+    obj &&
+    typeof obj === "object" &&
+    !Array.isArray(obj) &&
+    !isBuffer &&
+    !(obj instanceof ArrayBuffer) &&
+    !isBlob
+  );
+};
diff --git a/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useFetchx.ts b/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useFetchx.ts
new file mode 100644
index 00000000..58017a04
--- /dev/null
+++ b/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useFetchx.ts
@@ -0,0 +1,10 @@
+import { createContext, useContext } from "react";
+import { FetchxContext } from "../common/fetchx";
+
+const FetchxContextReact = createContext(null);
+
+export const FetchxProvider = FetchxContextReact.Provider;
+
+export function useFetchxContext(): FetchxContext | null {
+  return useContext(FetchxContextReact);
+}
diff --git a/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useSse.ts b/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useSse.ts
new file mode 100644
index 00000000..3c13f623
--- /dev/null
+++ b/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useSse.ts
@@ -0,0 +1,68 @@
+import { useEffect, useRef, useState } from "react";
+import type { TypedRequestInit } from "../common/fetchx";
+
+export interface UseSSEResult {
+  messages: Array;
+  error?: Error | null;
+  cancel: () => void;
+  restart: () => void;
+}
+
+type SseFetchFn = (
+  onMessage?: (ev: MessageEvent) => void,
+  qs?: Q,
+  init?: TypedRequestInit,
+  overrideUrl?: string,
+) => Promise;
+
+export function useSse(
+  fetchFn: SseFetchFn,
+  props?: {
+    qs?: Q;
+    init?: TypedRequestInit;
+    overrideUrl?: string;
+  },
+) {
+  const acRef = useRef(null);
+
+  const [state, setState] = useState>>({
+    messages: [],
+  });
+
+  const create = () => {
+    const ac = new AbortController();
+    acRef.current = ac;
+
+    setState({ messages: [], error: null }); // reset on new stream
+
+    fetchFn(
+      (ev) => {
+        setState((value) => {
+          const next = ev.data as T;
+          if ((value.messages || []).includes(next)) return value;
+          return { ...value, messages: [...(value.messages || []), next] };
+        });
+      },
+      props?.qs,
+      { ...(props?.init || {}), signal: ac.signal },
+      props?.overrideUrl,
+    ).catch((err) => setState((v) => ({ ...v, error: err as Error })));
+
+    return () => acRef.current?.abort();
+  };
+
+  useEffect(() => {
+    return create();
+  }, []);
+
+  const cancel = () => {
+    acRef.current?.abort();
+  };
+
+  const restart = () => {
+    cancel();
+    create();
+  };
+
+  return { ...state, cancel, restart, messages: state.messages as T[] };
+}
diff --git a/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useWebSocketX.ts b/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useWebSocketX.ts
new file mode 100644
index 00000000..8b8696a5
--- /dev/null
+++ b/examples/js/test-artifacts/http-envelop-test-output/sdk/react/useWebSocketX.ts
@@ -0,0 +1,104 @@
+import { useEffect, useRef, useState, useCallback } from "react";
+import { WebSocketX } from "../common/WebSocketX";
+
+export type UseWebSocketResult = {
+  send: (msg: TSend) => void;
+  close: () => void;
+  restart: () => void;
+  socket?: WebSocketX;
+} & UseWebSocketState;
+
+interface UseWebSocketState {
+  messages: TRecv[];
+  isOpen: boolean;
+  error?: Event | null;
+}
+
+export function useWebSocketX(
+  fn: (
+    overrideUrl?: string | undefined,
+    qs?: TQuery | undefined,
+  ) => WebSocketX,
+): UseWebSocketResult {
+  const socketRef = useRef | null>(null);
+  const [state, setState] = useState>({
+    messages: [],
+    isOpen: false,
+    error: undefined,
+  });
+
+  const create = useCallback(() => {
+    const ws = fn();
+    socketRef.current = ws;
+
+    setState({
+      messages: [],
+      error: undefined,
+      isOpen: ws.readyState === ws.OPEN,
+    });
+
+    ws.addEventListener("message", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          messages: [...prev.messages, ev.data],
+        };
+      });
+    });
+
+    ws.addEventListener("error", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          error: ev,
+        };
+      });
+    });
+
+    ws.addEventListener("open", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: true,
+        };
+      });
+    });
+
+    ws.addEventListener("close", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: false,
+        };
+      });
+    });
+
+    return ws;
+  }, []);
+
+  useEffect(() => {
+    const ws = create();
+    return () => ws.close();
+  }, [create]);
+
+  const send = (msg: TSend) => {
+    socketRef.current?.send(msg);
+  };
+
+  const close = () => {
+    socketRef.current?.close();
+  };
+
+  const restart = () => {
+    close();
+    create();
+  };
+
+  return {
+    ...state,
+    send,
+    close,
+    restart,
+    socket: socketRef.current || undefined,
+  };
+}
diff --git a/examples/js/test-artifacts/web-socket-test-output/UserStreamAction.ts b/examples/js/test-artifacts/web-socket-test-output/UserStreamAction.ts
index af64e4b6..7be071f8 100644
--- a/examples/js/test-artifacts/web-socket-test-output/UserStreamAction.ts
+++ b/examples/js/test-artifacts/web-socket-test-output/UserStreamAction.ts
@@ -17,15 +17,14 @@ export class UserStreamAction {
   static NewUrl = (qs?: URLSearchParams) =>
     buildUrl(UserStreamAction.URL, undefined, qs);
   static Method = "reactive";
-  static Create = (overrideUrl?: string, qs?: URLSearchParams) => {
+  static Create = (overrideUrl?: string, qs?: URLSearchParams, options) => {
     const url = overrideUrl ?? UserStreamAction.NewUrl(qs);
-    return new WebSocketX(
-      url,
-      undefined,
-      {
-        MessageFactoryClass: UserStreamActionRes,
-      },
-    );
+    const Cls = options?.SocketClass
+      ? options.SocketClass
+      : WebSocketX;
+    return new Cls(url, undefined, {
+      MessageFactoryClass: UserStreamActionRes,
+    });
   };
   static Definition = {
     name: "userStream",
diff --git a/examples/js/test-artifacts/web-socket-test-output/sdk/common/URLSearchParamsX.ts b/examples/js/test-artifacts/web-socket-test-output/sdk/common/URLSearchParamsX.ts
new file mode 100644
index 00000000..6cd269cc
--- /dev/null
+++ b/examples/js/test-artifacts/web-socket-test-output/sdk/common/URLSearchParamsX.ts
@@ -0,0 +1,144 @@
+import { stringify, parse } from "qs";
+
+/**
+ * Extended URLSearchParams that stores data in a nested object
+ * and keeps compatibility with URLSearchParams methods.
+ */
+export class URLSearchParamsX extends URLSearchParams {
+  /** Internal data store */
+  private data: Record = {};
+
+  constructor(
+    init?: string[][] | Record | string | URLSearchParams,
+  ) {
+    super(init);
+    if (init) {
+      if (typeof init === "string") {
+        Object.assign(this.data, parse(init));
+      } else if (init instanceof URLSearchParams) {
+        Object.assign(this.data, parse(init.toString()));
+      } else if (Array.isArray(init)) {
+        init.forEach(([k, v]) => (this.data[k] = v));
+      } else {
+        Object.assign(this.data, init);
+      }
+    }
+  }
+
+  /** Remove a key from the store */
+  override delete(name: string): void {
+    delete this.data[name];
+  }
+
+  /** Append a value to an array or create a new array */
+  override append(name: string, value: string): void {
+    if (this.data[name] === undefined) this.data[name] = value;
+    else if (Array.isArray(this.data[name])) this.data[name].push(value);
+    else this.data[name] = [this.data[name], value];
+  }
+
+  /** Get an iterator of top-level keys */
+  override keys(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        yield key;
+      }
+      return undefined;
+    })();
+  }
+
+  /** Number of top-level keys */
+  override get size(): number {
+    return Object.keys(this.data).length;
+  }
+
+  /** Sort top-level keys */
+  override sort(): void {
+    const sorted: Record = {};
+    Object.keys(this.data)
+      .sort()
+      .forEach((key) => {
+        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+        sorted[key] = this.data[key];
+      });
+    this.data = sorted;
+  }
+
+  /** Get an iterator of top-level values */
+  override values(): URLSearchParamsIterator {
+    const obj = this.data;
+    return (function* (): Generator {
+      for (const key of Object.keys(obj)) {
+        const val = obj[key];
+        // Make sure val is string
+        yield String(val);
+      }
+      return undefined;
+    })();
+  }
+
+  /** Get a single value by key */
+  override get(name: string): string | null {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val == null) return null;
+    return Array.isArray(val) ? String(val[0]) : String(val);
+  }
+
+  /** Check if key exists */
+  override has(name: string): boolean {
+    return this.data[name] !== undefined;
+  }
+
+  /** Iterate over top-level keys and values */
+  override forEach(
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    callbackfn: (value: any, key: string, parent: any) => void,
+  ): void {
+    for (const key of Object.keys(this.data)) {
+      callbackfn(this.data[key], key, this);
+    }
+  }
+
+  /** Get all values for a key as array */
+  override getAll(name: string): string[] {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    const val = this.data[name];
+    if (val === undefined) return [];
+    return Array.isArray(val) ? val.map(String) : [String(val)];
+  }
+
+  /** Get an iterator of key/value pairs (flattened) */
+  override entries() {
+    const params = new URLSearchParams(stringify(this.data));
+    return params.entries();
+  }
+
+  /** Convert to query string */
+  override toString(): string {
+    return stringify(this.data);
+  }
+
+  /** Set a key to a value */
+  override set(name: string, value: any): this {
+    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+    this.data[name] = value;
+    return this;
+  }
+
+  /** Convert entries to plain object */
+  toObject(): Record {
+    return Object.fromEntries(this.entries());
+  }
+
+  // eslint-disable-next-line no-unused-private-class-members
+  protected getTyped(key: string, type: string) {
+    const val = this.get(key);
+    if (val == null) return null;
+    const t = type.toLowerCase();
+    if (t.includes("number")) return Number(val);
+    if (t.includes("bool")) return val === "true";
+    return val;
+  }
+}
diff --git a/examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketWasm.ts b/examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketWasm.ts
new file mode 100644
index 00000000..b4b63e1e
--- /dev/null
+++ b/examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketWasm.ts
@@ -0,0 +1,125 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+
+// The Go-WASM reactor installs these globals on `window`. Declare them so the
+// bridge calls below type-check.
+declare global {
+  interface Window {
+    wasmWsOpen?: (
+      path: string,
+      query: string,
+      onMessage: (data: string) => void,
+      onClose: (reason: string) => void,
+    ) => number;
+    wasmWsSend: (id: number, data: string) => void;
+    wasmWsClose: (id: number) => void;
+  }
+}
+
+export class WebSocketWasm extends EventTarget {
+  static readonly CONNECTING = 0;
+  static readonly OPEN = 1;
+  static readonly CLOSING = 2;
+  static readonly CLOSED = 3;
+
+  url: string;
+  readyState: number;
+  onopen: ((ev: Event) => void) | null;
+  onmessage: ((ev: MessageEvent) => void) | null;
+  onerror: ((ev: Event) => void) | null;
+  onclose: ((ev: CloseEvent) => void) | null;
+  private _id: number;
+
+  constructor(url: string, _protocols?: string | string[]) {
+    super();
+    this.url = url;
+    this.readyState = WebSocketWasm.CONNECTING;
+    this.onopen = null;
+    this.onmessage = null;
+    this.onerror = null;
+    this.onclose = null;
+    this._id = -1;
+
+    const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+    const path = u.pathname;
+    const query = u.search.replace(/^\?/, "");
+
+    // Defer so listeners attached right after `new` still catch 'open', exactly
+    // like the native async connect.
+    queueMicrotask(() => this._open(path, query));
+  }
+
+  private _open(path: string, query: string): void {
+    const onMessage = (data: string): void => {
+      const ev = new MessageEvent("message", { data });
+      this.onmessage?.(ev);
+      this.dispatchEvent(ev);
+    };
+    const onClose = (reason: string): void => {
+      if (this.readyState === WebSocketWasm.CLOSED) return;
+      this.readyState = WebSocketWasm.CLOSED;
+      const ev = new CloseEvent("close", {
+        reason,
+        code: 1000,
+        wasClean: true,
+      });
+      this.onclose?.(ev);
+      this.dispatchEvent(ev);
+    };
+
+    if (typeof window.wasmWsOpen !== "function") {
+      return this._fail("reactor not ready (window.wasmWsOpen missing)");
+    }
+
+    this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+    if (this._id < 0) {
+      return this._fail(`no reactive handler registered for "${path}"`);
+    }
+
+    this.readyState = WebSocketWasm.OPEN;
+    const ev = new Event("open");
+    this.onopen?.(ev);
+    this.dispatchEvent(ev);
+  }
+
+  private _fail(message: string): void {
+    this.readyState = WebSocketWasm.CLOSED;
+    const err: Event & { message?: string } = new Event("error");
+    err.message = message;
+    this.onerror?.(err);
+    this.dispatchEvent(err);
+    const close = new CloseEvent("close", {
+      reason: message,
+      code: 1006,
+      wasClean: false,
+    });
+    this.onclose?.(close);
+    this.dispatchEvent(close);
+  }
+
+  send(data: unknown): void {
+    if (this.readyState !== WebSocketWasm.OPEN) {
+      throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+    }
+    // Strings pass through; everything else is stringified for now. Real binary
+    // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+    window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+  }
+
+  close(_code?: number, _reason?: string): void {
+    if (
+      this.readyState === WebSocketWasm.CLOSING ||
+      this.readyState === WebSocketWasm.CLOSED
+    ) {
+      return;
+    }
+    this.readyState = WebSocketWasm.CLOSING;
+    if (this._id >= 0) window.wasmWsClose(this._id);
+  }
+}
diff --git a/examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketX.ts b/examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketX.ts
index f2129df0..9b0544f6 100644
--- a/examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketX.ts
+++ b/examples/js/test-artifacts/web-socket-test-output/sdk/common/WebSocketX.ts
@@ -47,7 +47,10 @@ export class WebSocketX<
       data instanceof ArrayBuffer ||
       ArrayBuffer.isView(data)
     ) {
-      super.send(data);
+      // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+      // parameterizes BufferSource as ArrayBufferView, so the
+      // ArrayBufferLike-backed view from isView() needs widening on forward.
+      super.send(data as Parameters[0]);
     } else if (data !== undefined && data !== null) {
       super.send(data.toString());
     }
@@ -66,10 +69,13 @@ export class WebSocketX<
     options?: boolean | AddEventListenerOptions,
   ): void;
 
-  // implementation
+  // implementation (signature is not part of the public overload set, so it is
+  // widened to encompass the overloads above under strictFunctionTypes)
   addEventListener(
     type: string,
-    listener: EventListenerOrEventListenerObject,
+    listener:
+      | EventListenerOrEventListenerObject
+      | ((this: WebSocket, ev: any) => unknown),
     options?: boolean | AddEventListenerOptions,
   ): void {
     if (type === "message") {
diff --git a/examples/js/test-artifacts/web-socket-test-output/sdk/js/is-plausible-object.ts b/examples/js/test-artifacts/web-socket-test-output/sdk/js/is-plausible-object.ts
new file mode 100644
index 00000000..2fc6200d
--- /dev/null
+++ b/examples/js/test-artifacts/web-socket-test-output/sdk/js/is-plausible-object.ts
@@ -0,0 +1,25 @@
+/**
+ * Used in fetch context, to detect if the response is not a buffer
+ * or arraybufer, then create class instance of it.
+ * In such cases when response is blob, its better to pass the original classes to caller.
+ * @param obj
+ * @returns
+ */
+export const isPlausibleObject = (obj: any) => {
+  const isBuffer =
+    typeof globalThis.Buffer !== "undefined" &&
+    typeof globalThis.Buffer.isBuffer === "function" &&
+    globalThis.Buffer.isBuffer(obj);
+
+  const isBlob =
+    typeof globalThis.Blob !== "undefined" && obj instanceof globalThis.Blob;
+
+  return (
+    obj &&
+    typeof obj === "object" &&
+    !Array.isArray(obj) &&
+    !isBuffer &&
+    !(obj instanceof ArrayBuffer) &&
+    !isBlob
+  );
+};
diff --git a/examples/js/test-artifacts/web-socket-test-output/sdk/react/useFetchx.ts b/examples/js/test-artifacts/web-socket-test-output/sdk/react/useFetchx.ts
new file mode 100644
index 00000000..58017a04
--- /dev/null
+++ b/examples/js/test-artifacts/web-socket-test-output/sdk/react/useFetchx.ts
@@ -0,0 +1,10 @@
+import { createContext, useContext } from "react";
+import { FetchxContext } from "../common/fetchx";
+
+const FetchxContextReact = createContext(null);
+
+export const FetchxProvider = FetchxContextReact.Provider;
+
+export function useFetchxContext(): FetchxContext | null {
+  return useContext(FetchxContextReact);
+}
diff --git a/examples/js/test-artifacts/web-socket-test-output/sdk/react/useSse.ts b/examples/js/test-artifacts/web-socket-test-output/sdk/react/useSse.ts
new file mode 100644
index 00000000..3c13f623
--- /dev/null
+++ b/examples/js/test-artifacts/web-socket-test-output/sdk/react/useSse.ts
@@ -0,0 +1,68 @@
+import { useEffect, useRef, useState } from "react";
+import type { TypedRequestInit } from "../common/fetchx";
+
+export interface UseSSEResult {
+  messages: Array;
+  error?: Error | null;
+  cancel: () => void;
+  restart: () => void;
+}
+
+type SseFetchFn = (
+  onMessage?: (ev: MessageEvent) => void,
+  qs?: Q,
+  init?: TypedRequestInit,
+  overrideUrl?: string,
+) => Promise;
+
+export function useSse(
+  fetchFn: SseFetchFn,
+  props?: {
+    qs?: Q;
+    init?: TypedRequestInit;
+    overrideUrl?: string;
+  },
+) {
+  const acRef = useRef(null);
+
+  const [state, setState] = useState>>({
+    messages: [],
+  });
+
+  const create = () => {
+    const ac = new AbortController();
+    acRef.current = ac;
+
+    setState({ messages: [], error: null }); // reset on new stream
+
+    fetchFn(
+      (ev) => {
+        setState((value) => {
+          const next = ev.data as T;
+          if ((value.messages || []).includes(next)) return value;
+          return { ...value, messages: [...(value.messages || []), next] };
+        });
+      },
+      props?.qs,
+      { ...(props?.init || {}), signal: ac.signal },
+      props?.overrideUrl,
+    ).catch((err) => setState((v) => ({ ...v, error: err as Error })));
+
+    return () => acRef.current?.abort();
+  };
+
+  useEffect(() => {
+    return create();
+  }, []);
+
+  const cancel = () => {
+    acRef.current?.abort();
+  };
+
+  const restart = () => {
+    cancel();
+    create();
+  };
+
+  return { ...state, cancel, restart, messages: state.messages as T[] };
+}
diff --git a/examples/js/test-artifacts/web-socket-test-output/sdk/react/useWebSocketX.ts b/examples/js/test-artifacts/web-socket-test-output/sdk/react/useWebSocketX.ts
new file mode 100644
index 00000000..8b8696a5
--- /dev/null
+++ b/examples/js/test-artifacts/web-socket-test-output/sdk/react/useWebSocketX.ts
@@ -0,0 +1,104 @@
+import { useEffect, useRef, useState, useCallback } from "react";
+import { WebSocketX } from "../common/WebSocketX";
+
+export type UseWebSocketResult = {
+  send: (msg: TSend) => void;
+  close: () => void;
+  restart: () => void;
+  socket?: WebSocketX;
+} & UseWebSocketState;
+
+interface UseWebSocketState {
+  messages: TRecv[];
+  isOpen: boolean;
+  error?: Event | null;
+}
+
+export function useWebSocketX(
+  fn: (
+    overrideUrl?: string | undefined,
+    qs?: TQuery | undefined,
+  ) => WebSocketX,
+): UseWebSocketResult {
+  const socketRef = useRef | null>(null);
+  const [state, setState] = useState>({
+    messages: [],
+    isOpen: false,
+    error: undefined,
+  });
+
+  const create = useCallback(() => {
+    const ws = fn();
+    socketRef.current = ws;
+
+    setState({
+      messages: [],
+      error: undefined,
+      isOpen: ws.readyState === ws.OPEN,
+    });
+
+    ws.addEventListener("message", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          messages: [...prev.messages, ev.data],
+        };
+      });
+    });
+
+    ws.addEventListener("error", (ev) => {
+      setState((prev) => {
+        return {
+          ...prev,
+          error: ev,
+        };
+      });
+    });
+
+    ws.addEventListener("open", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: true,
+        };
+      });
+    });
+
+    ws.addEventListener("close", () => {
+      setState((prev) => {
+        return {
+          ...prev,
+          isOpen: false,
+        };
+      });
+    });
+
+    return ws;
+  }, []);
+
+  useEffect(() => {
+    const ws = create();
+    return () => ws.close();
+  }, [create]);
+
+  const send = (msg: TSend) => {
+    socketRef.current?.send(msg);
+  };
+
+  const close = () => {
+    socketRef.current?.close();
+  };
+
+  const restart = () => {
+    close();
+    create();
+  };
+
+  return {
+    ...state,
+    send,
+    close,
+    restart,
+    socket: socketRef.current || undefined,
+  };
+}
diff --git a/lib/golang/go-action-reactive-gin-realms.go b/lib/golang/go-action-reactive-gin-realms.go
new file mode 100644
index 00000000..8dd53771
--- /dev/null
+++ b/lib/golang/go-action-reactive-gin-realms.go
@@ -0,0 +1,50 @@
+package golang
+
+import (
+	"strings"
+
+	"github.com/torabian/emi/lib/core"
+)
+
+type goActionReactiveGinRealms struct {
+	ActionName    string
+	PackageName   string
+	PathParameter *core.CodeChunkCompiled
+	QueryParams   *core.CodeChunkCompiled
+	SafeUrl       string
+	SkipGinWasm   bool
+}
+
+var DEFAULT_GO_PACKAGE = "external"
+
+func GoActionReactiveGinRealms(
+	action core.EmiRpcAction,
+	ctx core.MicroGenContext,
+	complexes []RecognizedComplex,
+
+) (goActionReactiveGinRealms, []core.CodeChunkDependency, error) {
+
+	f := GetCommonFlags(ctx)
+
+	deps := []core.CodeChunkDependency{
+		{
+			Location: "github.com/gin-gonic/gin",
+		},
+		{
+			Location: "net/http",
+		},
+		{
+			Location: "net/url",
+		},
+	}
+
+	realms := goActionReactiveGinRealms{
+		ActionName:  core.ToUpper(core.NormaliseKey(action.GetName())),
+		PackageName: f.PackageName,
+		SafeUrl:     core.RemoveTypeAnnotations(action.GetUrl()),
+	}
+
+	realms.SkipGinWasm = strings.Contains(ctx.Tags, "skip-wasm-gin")
+
+	return realms, deps, nil
+}
diff --git a/lib/golang/go-action-reactive-gin-render.go b/lib/golang/go-action-reactive-gin-render.go
new file mode 100644
index 00000000..e8a337f9
--- /dev/null
+++ b/lib/golang/go-action-reactive-gin-render.go
@@ -0,0 +1,337 @@
+package golang
+
+import (
+	"bytes"
+	"text/template"
+
+	"github.com/torabian/emi/lib/core"
+)
+
+func GoActionRenderReactiveGin(
+	action core.EmiRpcAction,
+	ctx core.MicroGenContext,
+	complexes []RecognizedComplex,
+) (*core.CodeChunkCompiled, error) {
+
+	realms, deps, err := GoActionReactiveGinRealms(action, ctx, complexes)
+	if err != nil {
+		return nil, err
+	}
+
+	// For socket, we need some extra dependencies
+	deps = append(deps, core.CodeChunkDependency{
+		Location: "github.com/gorilla/websocket",
+	},
+
+		core.CodeChunkDependency{
+			Location: "crypto/tls",
+		},
+
+		core.CodeChunkDependency{
+			Location: "unicode/utf8",
+		})
+
+	res := &core.CodeChunkCompiled{
+		Tokens: []core.GeneratedScriptToken{
+			{
+				Name:  core.TOKEN_ORIGINAL_NAME,
+				Value: realms.ActionName,
+			},
+		},
+	}
+
+	const tmpl = `
+{{ if .realms.SkipGinWasm }}
+//go:build !wasm
+{{ end }}
+	
+/**
+* Action to communicate with the action {{ .realms.ActionName }}
+*/
+
+{{ define "upgradeSequence" }}
+
+	{{ if .realms.PathParameter }}
+	pathParams := {{ .realms.ActionName }}PathParameterFromGin(c)
+	{{ end }}
+
+	ws, err := upgrader{{ .realms.ActionName }}.Upgrade(c.Writer, c.Request, nil)
+	if err != nil {
+		c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot upgrade websocket"})
+		return
+	}
+{{ end }}
+
+
+// WebSocket upgrader
+var upgrader{{ .realms.ActionName }} = websocket.Upgrader{
+	CheckOrigin: func(r *http.Request) bool { return true },
+}
+
+func (x *{{ .realms.ActionName }}Message) Connection() *websocket.Conn {
+	return x.Conn.(*websocket.Conn)
+}
+
+func (x *{{ .realms.ActionName }}ClientSession) Connection() *websocket.Conn {
+	return x.Socket.(*websocket.Conn)
+}
+
+func (x *{{ .realms.ActionName }}Session) GinCtx() *gin.Context {
+	return x.Ctx.(*gin.Context)
+}
+
+func (x *{{ .realms.ActionName }}Session) GetSocket() *websocket.Conn {
+	return x.Socket.(*websocket.Conn)
+}
+
+// Generated handler
+func {{ .realms.ActionName }}Gin(r *gin.Engine, factory func(
+	session {{ .realms.ActionName }}Session,
+) (chan []byte, error)) {
+	meta := {{ .realms.ActionName }}Meta()
+	r.GET(meta.URL, {{ .realms.ActionName }}ReactiveHandler(factory))
+}
+
+
+func {{ .realms.ActionName }}ReactiveHandler(factory func(
+	session {{ .realms.ActionName }}Session,
+) (chan []byte, error)) gin.HandlerFunc {
+
+	return func(ctx *gin.Context) {
+
+		read := make(chan {{ .realms.ActionName }}ReadChan)
+		done := make(chan bool)
+
+		c, err := upgrader{{ .realms.ActionName }}.Upgrade(ctx.Writer, ctx.Request, nil)
+		if err != nil {
+			c.WriteMessage(websocket.TextMessage, []byte(err.Error()))
+
+			c.Close()
+			return
+		}
+
+		session := {{ .realms.ActionName }}Session{
+			Ctx:    ctx,
+			Socket: c,
+			Done:   done,
+			Read:   read,
+		}
+		session.QueryParams = {{ .realms.ActionName }}QueryFromHttp(ctx.Request)
+
+		write, err := factory(session)
+
+		if err != nil {
+			c.WriteMessage(websocket.TextMessage, []byte(err.Error()))
+		}
+
+		go func() {
+			for {
+				_, data, err := c.ReadMessage()
+				read <- {{ .realms.ActionName }}ReadChan{
+					Data:  data,
+					Error: err,
+				}
+
+				if err != nil {
+					return
+				}
+			}
+		}()
+
+		go func() {
+			for {
+				select {
+				case msg, ok := <-write:
+					if !ok {
+						// Channel closed; shutdown
+						c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+						done <- true
+						return
+					}
+					msgType := websocket.TextMessage
+					if !utf8.Valid(msg) {
+						msgType = websocket.BinaryMessage
+					}
+					err := c.WriteMessage(msgType, msg)
+
+					if err != nil {
+						// Optionally log the error or send to a logger
+						done <- true
+						return
+					}
+				case <-done:
+					c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+					return
+				}
+			}
+		}()
+	}
+}
+
+// {{ .realms.ActionName }}ClientOptions configures a client dial. All fields are
+// optional — pass a zero value for a plaintext, header-less ws:// connection.
+//
+// TLSConfig governs the TLS handshake when dialing wss://. Set Certificates
+// and RootCAs (and optionally ServerName) for mTLS; leave nil for ws://.
+type {{ .realms.ActionName }}ClientOptions struct {
+	Query     url.Values
+	TLSConfig *tls.Config
+	Headers   http.Header
+}
+
+// {{ .realms.ActionName }}Client dials the {{ .realms.ActionName }} endpoint at baseURL
+// (e.g. "ws://localhost:8080" or "https://host" — http/https are auto-rewritten
+// to ws/wss) and returns a session whose channels behave like the server's.
+//
+// Connect, then read and write concurrently. The Read goroutine bails on
+// msg.Error (server closed, network drop, etc.); the Done channel fires once
+// for any disconnect — use it to unblock main or trigger reconnect logic.
+//
+// For mTLS, build a *tls.Config with the client keypair + server CA and pass
+// it via opts.TLSConfig. The handshake completes before the websocket upgrade
+// is sent, so a bad cert fails this call rather than later on Read/Write.
+//
+//	sess, err := {{ .realms.ActionName }}Client(
+//	    "wss://hub.example.com",
+//	    {{ .realms.ActionName }}ClientOptions{TLSConfig: tlsCfg},
+//	)
+//	if err != nil {
+//	    log.Fatal(err)
+//	}
+//
+//	// Reader: pull frames off sess.Read until error.
+//	go func() {
+//	    for {
+//	        msg := <-sess.Read
+//	        if msg.Error != nil {
+//	            log.Println("read error:", msg.Error)
+//	            return
+//	        }
+//	        log.Printf("server sent %d bytes: %s", len(msg.Data), msg.Data)
+//	    }
+//	}()
+//
+//	// Writer: send frames whenever you have something to say. Bytes that
+//	// aren't valid UTF-8 are sent as binary frames automatically.
+//	sess.Write <- []byte("hello server")
+//
+//	// Block until the connection drops, then exit. Alternatively, close
+//	// sess.Write to initiate a clean shutdown from the client side:
+//	//   close(sess.Write)
+//	<-sess.Done
+func {{ .realms.ActionName }}Client(baseURL string, opts *{{ .realms.ActionName }}ClientOptions) (*{{ .realms.ActionName }}ClientSession, error) {
+	u, err := url.Parse(baseURL)
+	if err != nil {
+		return nil, err
+	}
+	switch u.Scheme {
+	case "http":
+		u.Scheme = "ws"
+	case "https":
+		u.Scheme = "wss"
+	}
+	u.Path = {{ .realms.ActionName }}Meta().URL
+	if opts != nil && opts.Query != nil {
+		u.RawQuery = opts.Query.Encode()
+	}
+
+	var headers http.Header
+
+	if opts != nil {
+		headers = opts.Headers
+	}
+
+	dialer := &websocket.Dialer{}
+
+	if opts != nil {
+		dialer.TLSClientConfig = opts.TLSConfig
+	}
+
+	c, _, err := dialer.Dial(u.String(), headers)
+	if err != nil {
+		return nil, err
+	}
+
+	session := &{{ .realms.ActionName }}ClientSession{
+		Socket: c,
+		Done:   make(chan bool, 1),
+		Read:   make(chan {{ .realms.ActionName }}ReadChan),
+		Write:  make(chan []byte, 16),
+	}
+
+	// Reader goroutine: pumps frames from the socket into Read. On error it
+	// forwards the error frame, signals Done, and exits.
+	go func() {
+		for {
+			_, data, err := c.ReadMessage()
+			session.Read <- {{ .realms.ActionName }}ReadChan{
+				Data:  data,
+				Error: err,
+			}
+			if err != nil {
+				select {
+				case session.Done <- true:
+				default:
+				}
+				return
+			}
+		}
+	}()
+
+	// Writer goroutine: drains Write to the socket. Closing Write triggers a
+	// clean close handshake; an error or Done signal closes the socket.
+	go func() {
+		defer c.Close()
+		for {
+			select {
+			case msg, ok := <-session.Write:
+				if !ok {
+					c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+					select {
+					case session.Done <- true:
+					default:
+					}
+					return
+				}
+				msgType := websocket.TextMessage
+				if !utf8.Valid(msg) {
+					msgType = websocket.BinaryMessage
+				}
+				if err := c.WriteMessage(msgType, msg); err != nil {
+					select {
+					case session.Done <- true:
+					default:
+					}
+					return
+				}
+			case <-session.Done:
+				c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
+				return
+			}
+		}
+	}()
+
+	return session, nil
+}
+
+
+`
+
+	t := template.Must(template.New("action").Funcs(core.CommonMap).Parse(tmpl))
+
+	var buf bytes.Buffer
+	if err := t.Execute(&buf, core.H{
+		"action":       action,
+		"realms":       realms,
+		"shouldExport": true,
+	}); err != nil {
+		return nil, err
+	}
+
+	res.ActualScript = buf.Bytes()
+	res.SuggestedFileName = realms.ActionName + "Gin"
+	res.SuggestedExtension = ".go"
+	res.CodeChunkDependensies = deps
+
+	return res, nil
+}
diff --git a/lib/golang/go-action-reactive-realms.go b/lib/golang/go-action-reactive-realms.go
index 270b49f5..485b28ca 100644
--- a/lib/golang/go-action-reactive-realms.go
+++ b/lib/golang/go-action-reactive-realms.go
@@ -12,8 +12,6 @@ type goActionReactiveRealms struct {
 	SafeUrl       string
 }
 
-var DEFAULT_GO_PACKAGE = "external"
-
 func GoActionReactiveRealms(
 	action core.EmiRpcAction,
 	ctx core.MicroGenContext,
@@ -21,36 +19,18 @@ func GoActionReactiveRealms(
 
 ) (goActionReactiveRealms, []core.CodeChunkDependency, error) {
 
-	type Flags struct {
-		Emigo       string `json:"emigo,omitempty"`
-		PackageName string `json:"pkg,omitempty"`
-	}
-	var f Flags = Flags{
-		Emigo:       "github.com/torabian/emi/emigo",
-		PackageName: DEFAULT_GO_PACKAGE,
-	}
-
-	if val, ok := ctx.Flags["emigo"]; ok && val != "" {
-		f.Emigo = val
-	}
-
-	if val, ok := ctx.Flags["pkg"]; ok && val != "" {
-		f.PackageName = val
-	}
+	f := GetCommonFlags(ctx)
 
 	deps := []core.CodeChunkDependency{
 		{
-			Location: "github.com/gin-gonic/gin",
+			Location: f.Emigo,
 		},
 		{
-			Location: "fmt",
+			Location: "net/url",
 		},
 		{
 			Location: "net/http",
 		},
-		{
-			Location: f.Emigo,
-		},
 	}
 
 	realms := goActionReactiveRealms{
diff --git a/lib/golang/go-action-reactive-render.go b/lib/golang/go-action-reactive-render.go
index 48d2a0d8..5395c5ba 100644
--- a/lib/golang/go-action-reactive-render.go
+++ b/lib/golang/go-action-reactive-render.go
@@ -2,6 +2,7 @@ package golang
 
 import (
 	"bytes"
+	"strings"
 	"text/template"
 
 	"github.com/torabian/emi/lib/core"
@@ -11,26 +12,13 @@ func GoActionRenderReactive(
 	action core.EmiRpcAction,
 	ctx core.MicroGenContext,
 	complexes []RecognizedComplex,
-) (*core.CodeChunkCompiled, error) {
+) ([]*core.CodeChunkCompiled, error) {
 
 	realms, deps, err := GoActionReactiveRealms(action, ctx, complexes)
 	if err != nil {
 		return nil, err
 	}
 
-	// For socket, we need some extra dependencies
-	deps = append(deps, core.CodeChunkDependency{
-		Location: "github.com/gorilla/websocket",
-	},
-
-		core.CodeChunkDependency{
-			Location: "crypto/tls",
-		},
-
-		core.CodeChunkDependency{
-			Location: "unicode/utf8",
-		})
-
 	res := &core.CodeChunkCompiled{
 		Tokens: []core.GeneratedScriptToken{
 			{
@@ -43,19 +31,7 @@ func GoActionRenderReactive(
 	const tmpl = `/**
 * Action to communicate with the action {{ .realms.ActionName }}
 */
-
-{{ define "upgradeSequence" }}
-
-	{{ if .realms.PathParameter }}
-	pathParams := {{ .realms.ActionName }}PathParameterFromGin(c)
-	{{ end }}
-
-	ws, err := upgrader{{ .realms.ActionName }}.Upgrade(c.Writer, c.Request, nil)
-	if err != nil {
-		c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot upgrade websocket"})
-		return
-	}
-{{ end }}
+ 
 
 func {{ .realms.ActionName }}Meta() struct {
     Name   string
@@ -88,15 +64,11 @@ func {{ .realms.ActionName }}Meta() struct {
 {{ end }}
 
 
-// WebSocket upgrader
-var upgrader{{ .realms.ActionName }} = websocket.Upgrader{
-	CheckOrigin: func(r *http.Request) bool { return true },
-}
-
 
 type {{ .realms.ActionName }}Message struct {
 	Raw []byte
-	Conn *websocket.Conn	
+	// Conn *websocket.Conn	
+	Conn interface{}
 	MessageType int
 	Error error
 	{{ if .realms.PathParameter }}
@@ -107,42 +79,11 @@ type {{ .realms.ActionName }}Message struct {
 // Developer handler type
 type {{ .realms.ActionName }}Handler func(msg {{ .realms.ActionName }}Message ) error
 
-// Generated handler
-func {{ .realms.ActionName }}(r *gin.Engine, handler {{ .realms.ActionName }}Handler) {
-	meta := {{ .realms.ActionName }}Meta()
-	r.GET(meta.URL, func(c *gin.Context) {
-		{{ template "upgradeSequence" . }}
-
-		defer ws.Close()
-
-		for {
-			mt, raw, err := ws.ReadMessage()
-			msg := {{ .realms.ActionName }}Message{
-				Conn: ws,
-				Raw: raw,
-				Error: err,
-				MessageType: mt,
-			}
-
-			{{ if .realms.PathParameter }}
-			msg.PathParams = pathParams
-			{{ end}}
-
-			
-			// Provide raw message to developer handler
-			if err := handler(msg); err != nil {
-				errMsg := fmt.Sprintf("handler error: %v", err)
-				if writeErr := ws.WriteMessage(mt, []byte(errMsg)); writeErr != nil {
-					break
-				}
-			}
-		}
-	})
-}
-
 type {{ .realms.ActionName }}Session struct {
-	Ctx    *gin.Context
-	Socket *websocket.Conn
+	// Ctx    *gin.Context
+	// Socket *websocket.Conn
+	Ctx    interface{}
+	Socket interface{}
 	Done   chan bool
 	Read   chan {{ .realms.ActionName }}ReadChan
 	QueryParams {{ .realms.ActionName }}Query
@@ -150,88 +91,12 @@ type {{ .realms.ActionName }}Session struct {
 
 type {{ .realms.ActionName }}HandlerDuplex func(*{{ .realms.ActionName }}Session)
 
-
 type {{ .realms.ActionName }}ReadChan struct {
 	Data  []byte
 	Error error
+	MessageType int
 }
-
-
-func {{ .realms.ActionName }}ReactiveHandler(factory func(
-	session {{ .realms.ActionName }}Session,
-) (chan []byte, error)) gin.HandlerFunc {
-
-	return func(ctx *gin.Context) {
-
-		read := make(chan {{ .realms.ActionName }}ReadChan)
-		done := make(chan bool)
-
-		c, err := upgrader{{ .realms.ActionName }}.Upgrade(ctx.Writer, ctx.Request, nil)
-		if err != nil {
-			c.WriteMessage(websocket.TextMessage, []byte(err.Error()))
-
-			c.Close()
-			return
-		}
-
-		session := {{ .realms.ActionName }}Session{
-			Ctx:    ctx,
-			Socket: c,
-			Done:   done,
-			Read:   read,
-		}
-		session.QueryParams = {{ .realms.ActionName }}QueryFromGin(ctx)
-
-		write, err := factory(session)
-
-		if err != nil {
-			c.WriteMessage(websocket.TextMessage, []byte(err.Error()))
-		}
-
-		go func() {
-			for {
-				_, data, err := c.ReadMessage()
-				read <- {{ .realms.ActionName }}ReadChan{
-					Data:  data,
-					Error: err,
-				}
-
-				if err != nil {
-					return
-				}
-			}
-		}()
-
-		go func() {
-			for {
-				select {
-				case msg, ok := <-write:
-					if !ok {
-						// Channel closed; shutdown
-						c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
-						done <- true
-						return
-					}
-					msgType := websocket.TextMessage
-					if !utf8.Valid(msg) {
-						msgType = websocket.BinaryMessage
-					}
-					err := c.WriteMessage(msgType, msg)
-
-					if err != nil {
-						// Optionally log the error or send to a logger
-						done <- true
-						return
-					}
-				case <-done:
-					c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
-					return
-				}
-			}
-		}()
-	}
-}
-
+ 
 
 
 // {{ .realms.ActionName }}ClientSession is the client-side mirror of
@@ -240,159 +105,13 @@ func {{ .realms.ActionName }}ReactiveHandler(factory func(
 // fires when the server closes or the socket errors, so the caller can use it
 // as a single disconnect signal.
 type {{ .realms.ActionName }}ClientSession struct {
-	Socket *websocket.Conn
+	// Socket *websocket.Conn
+	Socket interface{}
 	Done   chan bool
 	Read   chan {{ .realms.ActionName }}ReadChan
 	Write  chan []byte
 }
 
-// {{ .realms.ActionName }}ClientOptions configures a client dial. All fields are
-// optional — pass a zero value for a plaintext, header-less ws:// connection.
-//
-// TLSConfig governs the TLS handshake when dialing wss://. Set Certificates
-// and RootCAs (and optionally ServerName) for mTLS; leave nil for ws://.
-type {{ .realms.ActionName }}ClientOptions struct {
-	Query     url.Values
-	TLSConfig *tls.Config
-	Headers   http.Header
-}
-
-// {{ .realms.ActionName }}Client dials the {{ .realms.ActionName }} endpoint at baseURL
-// (e.g. "ws://localhost:8080" or "https://host" — http/https are auto-rewritten
-// to ws/wss) and returns a session whose channels behave like the server's.
-//
-// Connect, then read and write concurrently. The Read goroutine bails on
-// msg.Error (server closed, network drop, etc.); the Done channel fires once
-// for any disconnect — use it to unblock main or trigger reconnect logic.
-//
-// For mTLS, build a *tls.Config with the client keypair + server CA and pass
-// it via opts.TLSConfig. The handshake completes before the websocket upgrade
-// is sent, so a bad cert fails this call rather than later on Read/Write.
-//
-//	sess, err := {{ .realms.ActionName }}Client(
-//	    "wss://hub.example.com",
-//	    {{ .realms.ActionName }}ClientOptions{TLSConfig: tlsCfg},
-//	)
-//	if err != nil {
-//	    log.Fatal(err)
-//	}
-//
-//	// Reader: pull frames off sess.Read until error.
-//	go func() {
-//	    for {
-//	        msg := <-sess.Read
-//	        if msg.Error != nil {
-//	            log.Println("read error:", msg.Error)
-//	            return
-//	        }
-//	        log.Printf("server sent %d bytes: %s", len(msg.Data), msg.Data)
-//	    }
-//	}()
-//
-//	// Writer: send frames whenever you have something to say. Bytes that
-//	// aren't valid UTF-8 are sent as binary frames automatically.
-//	sess.Write <- []byte("hello server")
-//
-//	// Block until the connection drops, then exit. Alternatively, close
-//	// sess.Write to initiate a clean shutdown from the client side:
-//	//   close(sess.Write)
-//	<-sess.Done
-func {{ .realms.ActionName }}Client(baseURL string, opts *{{ .realms.ActionName }}ClientOptions) (*{{ .realms.ActionName }}ClientSession, error) {
-	u, err := url.Parse(baseURL)
-	if err != nil {
-		return nil, err
-	}
-	switch u.Scheme {
-	case "http":
-		u.Scheme = "ws"
-	case "https":
-		u.Scheme = "wss"
-	}
-	u.Path = {{ .realms.ActionName }}Meta().URL
-	if opts != nil && opts.Query != nil {
-		u.RawQuery = opts.Query.Encode()
-	}
-
-	var headers http.Header
-
-	if opts != nil {
-		headers = opts.Headers
-	}
-
-	dialer := &websocket.Dialer{}
-
-	if opts != nil {
-		dialer.TLSClientConfig = opts.TLSConfig
-	}
-
-	c, _, err := dialer.Dial(u.String(), headers)
-	if err != nil {
-		return nil, err
-	}
-
-	session := &{{ .realms.ActionName }}ClientSession{
-		Socket: c,
-		Done:   make(chan bool, 1),
-		Read:   make(chan {{ .realms.ActionName }}ReadChan),
-		Write:  make(chan []byte, 16),
-	}
-
-	// Reader goroutine: pumps frames from the socket into Read. On error it
-	// forwards the error frame, signals Done, and exits.
-	go func() {
-		for {
-			_, data, err := c.ReadMessage()
-			session.Read <- {{ .realms.ActionName }}ReadChan{
-				Data:  data,
-				Error: err,
-			}
-			if err != nil {
-				select {
-				case session.Done <- true:
-				default:
-				}
-				return
-			}
-		}
-	}()
-
-	// Writer goroutine: drains Write to the socket. Closing Write triggers a
-	// clean close handshake; an error or Done signal closes the socket.
-	go func() {
-		defer c.Close()
-		for {
-			select {
-			case msg, ok := <-session.Write:
-				if !ok {
-					c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
-					select {
-					case session.Done <- true:
-					default:
-					}
-					return
-				}
-				msgType := websocket.TextMessage
-				if !utf8.Valid(msg) {
-					msgType = websocket.BinaryMessage
-				}
-				if err := c.WriteMessage(msgType, msg); err != nil {
-					select {
-					case session.Done <- true:
-					default:
-					}
-					return
-				}
-			case <-session.Done:
-				c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
-				return
-			}
-		}
-	}()
-
-	return session, nil
-}
-
-
 `
 
 	t := template.Must(template.New("action").Funcs(core.CommonMap).Parse(tmpl))
@@ -406,10 +125,33 @@ func {{ .realms.ActionName }}Client(baseURL string, opts *{{ .realms.ActionName
 		return nil, err
 	}
 
+	outputs := []*core.CodeChunkCompiled{}
+	enabledGin := !strings.Contains(ctx.Tags, "skip-gin")
+	if enabledGin {
+
+		reactiveGin, ginErr := GoActionRenderReactiveGin(action, ctx, complexes)
+		if ginErr != nil {
+			return nil, ginErr
+		}
+		if reactiveGin != nil {
+			outputs = append(outputs, reactiveGin)
+		}
+	}
+
+	reactiveWasm, ginErr := GoActionRenderReactiveWasm(action, ctx, complexes)
+	if ginErr != nil {
+		return nil, ginErr
+	}
+	if reactiveWasm != nil {
+		outputs = append(outputs, reactiveWasm)
+	}
+
 	res.ActualScript = buf.Bytes()
 	res.SuggestedFileName = realms.ActionName
 	res.SuggestedExtension = ".go"
 	res.CodeChunkDependensies = deps
 
-	return res, nil
+	outputs = append(outputs, res)
+
+	return outputs, nil
 }
diff --git a/lib/golang/go-action-reactive-wasm-render.go b/lib/golang/go-action-reactive-wasm-render.go
new file mode 100644
index 00000000..a6d389cc
--- /dev/null
+++ b/lib/golang/go-action-reactive-wasm-render.go
@@ -0,0 +1,115 @@
+package golang
+
+import (
+	"bytes"
+	"text/template"
+
+	"github.com/torabian/emi/lib/core"
+)
+
+type reactiveWasmRealms struct {
+	ActionName string
+}
+
+func GoActionRenderReactiveWasm(
+	action core.EmiRpcAction,
+	ctx core.MicroGenContext,
+	complexes []RecognizedComplex,
+) (*core.CodeChunkCompiled, error) {
+	realms := &reactiveWasmRealms{
+		ActionName: core.ToUpper(core.NormaliseKey(action.GetName())),
+	}
+
+	f := GetCommonFlags(ctx)
+
+	res := &core.CodeChunkCompiled{
+		CodeChunkDependensies: []core.CodeChunkDependency{
+			{
+				Location: f.Emigo,
+			},
+		},
+	}
+
+	const tmpl = `
+//go:build wasm
+
+// {{ .realms.ActionName }}ReactiveHandlerWasm is the in-browser counterpart of
+// {{ .realms.ActionName }}ReactiveHandler. It registers the same developer factory against an
+// emigo.WasmReactor instead of a gin engine, so the business logic is shared
+// verbatim across the real server and the wasm build.
+//
+// There is no gorilla, no gin, and no socket here: the reactor bridges the
+// session's channels straight to the WebSocketWasm JS class.
+func {{ .realms.ActionName }}ReactiveHandlerWasm(
+	reactor *emigo.WasmReactor,
+	factory func(session {{ .realms.ActionName }}Session) (chan []byte, error),
+) {
+	reactor.Handle({{ .realms.ActionName }}Meta().URL, func(conn *emigo.WasmReactiveConn) error {
+		session := {{ .realms.ActionName }}Session{
+			Done:        conn.Done,
+			Read:        make(chan {{ .realms.ActionName }}ReadChan),
+			QueryParams: {{ .realms.ActionName }}QueryFromString(conn.Query.Encode()),
+			// Socket and Ctx stay nil — meaningless in the browser.
+		}
+
+		// client -> server: adapt raw []byte frames into the typed read channel.
+		go func() {
+			for {
+				select {
+				case data, ok := <-conn.Read:
+					if !ok {
+						return
+					}
+					session.Read <- {{ .realms.ActionName }}ReadChan{Data: data}
+				case <-conn.Done:
+					return
+				}
+			}
+		}()
+
+		write, err := factory(session)
+		if err != nil {
+			return err
+		}
+
+		// server -> client: forward the factory's write channel to the bridge.
+		// Closing write signals a server-initiated close to the reactor.
+		go func() {
+			for {
+				select {
+				case msg, ok := <-write:
+					if !ok {
+						close(conn.Write)
+						return
+					}
+					conn.Write <- msg
+				case <-conn.Done:
+					return
+				}
+			}
+		}()
+
+		return nil
+	})
+}
+
+
+`
+
+	t := template.Must(template.New("action").Funcs(core.CommonMap).Parse(tmpl))
+
+	var buf bytes.Buffer
+	if err := t.Execute(&buf, core.H{
+		"action":       action,
+		"realms":       realms,
+		"shouldExport": true,
+	}); err != nil {
+		return nil, err
+	}
+
+	res.ActualScript = buf.Bytes()
+	res.SuggestedFileName = realms.ActionName + "Wasm"
+	res.SuggestedExtension = ".go"
+
+	return res, nil
+}
diff --git a/lib/golang/go-action-realms.go b/lib/golang/go-action-realms.go
index d0a6fdde..ca9fced2 100644
--- a/lib/golang/go-action-realms.go
+++ b/lib/golang/go-action-realms.go
@@ -46,22 +46,7 @@ func GoActionRealms(
 
 	skipGoClient := strings.Contains(ctx.Tags, GEN_GO_SKIP_CLIENT)
 
-	type Flags struct {
-		Emigo       string `json:"emigo,omitempty"`
-		PackageName string `json:"pkg,omitempty"`
-	}
-	var f Flags = Flags{
-		Emigo:       "github.com/torabian/emi/emigo",
-		PackageName: DEFAULT_GO_PACKAGE,
-	}
-
-	if val, ok := ctx.Flags["emigo"]; ok && val != "" {
-		f.Emigo = val
-	}
-
-	if val, ok := ctx.Flags["pkg"]; ok && val != "" {
-		f.PackageName = val
-	}
+	f := GetCommonFlags(ctx)
 
 	realms := goActionRealms{
 		ActionName: core.ToUpper(core.NormaliseKey(action.GetName())),
diff --git a/lib/golang/go-action-render.go b/lib/golang/go-action-render.go
index 769641c3..c36a527a 100644
--- a/lib/golang/go-action-render.go
+++ b/lib/golang/go-action-render.go
@@ -19,8 +19,9 @@ func GoActionRender(
 		if err != nil {
 			return nil, err
 		}
-		return []*core.CodeChunkCompiled{reactive}, nil
+		return reactive, nil
 	}
+
 	skipGoClient := strings.Contains(ctx.Tags, GEN_GO_SKIP_CLIENT)
 	splitGin := strings.Contains(ctx.Tags, "split-gin")
 	splitCli := strings.Contains(ctx.Tags, "split-cli")
diff --git a/lib/golang/go-common-flags.go b/lib/golang/go-common-flags.go
new file mode 100644
index 00000000..735ea292
--- /dev/null
+++ b/lib/golang/go-common-flags.go
@@ -0,0 +1,25 @@
+package golang
+
+import "github.com/torabian/emi/lib/core"
+
+type Flags struct {
+	Emigo       string `json:"emigo,omitempty"`
+	PackageName string `json:"pkg,omitempty"`
+}
+
+func GetCommonFlags(ctx core.MicroGenContext) Flags {
+	var f Flags = Flags{
+		Emigo:       "github.com/torabian/emi/emigo",
+		PackageName: DEFAULT_GO_PACKAGE,
+	}
+
+	if val, ok := ctx.Flags["emigo"]; ok && val != "" {
+		f.Emigo = val
+	}
+
+	if val, ok := ctx.Flags["pkg"]; ok && val != "" {
+		f.PackageName = val
+	}
+
+	return f
+}
diff --git a/lib/golang/go-config.go b/lib/golang/go-config.go
index 2dc528d1..0a2a7514 100644
--- a/lib/golang/go-config.go
+++ b/lib/golang/go-config.go
@@ -234,22 +234,7 @@ func (x *Config) Save(filepath string) error {
 
 	t := template.Must(template.New("config_generator").Funcs(core.CommonMap).Parse(tmpl))
 
-	type Flags struct {
-		Emigo       string `json:"emigo,omitempty"`
-		PackageName string `json:"pkg,omitempty"`
-	}
-	var f Flags = Flags{
-		Emigo:       "github.com/torabian/emi/emigo",
-		PackageName: DEFAULT_GO_PACKAGE,
-	}
-
-	if val, ok := ctx.Flags["emigo"]; ok && val != "" {
-		f.Emigo = val
-	}
-
-	if val, ok := ctx.Flags["pkg"]; ok && val != "" {
-		f.PackageName = val
-	}
+	f := GetCommonFlags(ctx)
 
 	if len(configs) > 0 {
 		res.CodeChunkDependensies = append(
diff --git a/lib/golang/go-manifest.go b/lib/golang/go-manifest.go
index df41a718..e4989949 100644
--- a/lib/golang/go-manifest.go
+++ b/lib/golang/go-manifest.go
@@ -131,22 +131,7 @@ func {{ upper .manifest.Name }}CliManifest() []*cli.Command {
 
 `
 
-	type Flags struct {
-		Emigo       string `json:"emigo,omitempty"`
-		PackageName string `json:"pkg,omitempty"`
-	}
-	var f Flags = Flags{
-		Emigo:       "github.com/torabian/emi/emigo",
-		PackageName: DEFAULT_GO_PACKAGE,
-	}
-
-	if val, ok := ctx.Flags["emigo"]; ok && val != "" {
-		f.Emigo = val
-	}
-
-	if val, ok := ctx.Flags["pkg"]; ok && val != "" {
-		f.PackageName = val
-	}
+	f := GetCommonFlags(ctx)
 
 	rendered := []manifestRender{}
 
diff --git a/lib/golang/go-public-api.go b/lib/golang/go-public-api.go
index 8ba4b196..9e67d71d 100644
--- a/lib/golang/go-public-api.go
+++ b/lib/golang/go-public-api.go
@@ -135,23 +135,7 @@ func (x GoModuleGenerationFlags) GetDtos() []string {
 func GoModuleFull(module *core.Emi, ctx core.MicroGenContext) ([]core.VirtualFile, error) {
 	globalPacakges := []string{"qs", "@types/qs"}
 
-	type Flags struct {
-		Emigo       string  `json:"emigo,omitempty"`
-		PackageName string  `json:"pkg,omitempty"`
-		Dtos        *string `json:"dtos"`
-	}
-	var f Flags = Flags{
-		Emigo:       "github.com/torabian/emi/emigo",
-		PackageName: DEFAULT_GO_PACKAGE,
-	}
-
-	if val, ok := ctx.Flags["emigo"]; ok && val != "" {
-		f.Emigo = val
-	}
-
-	if val, ok := ctx.Flags["pkg"]; ok && val != "" {
-		f.PackageName = val
-	}
+	f := GetCommonFlags(ctx)
 
 	complexes := DiscoverComplexes(module)
 	files := []core.VirtualFile{}
diff --git a/lib/golang/go-query-params.go b/lib/golang/go-query-params.go
index c89b29af..59668f2a 100644
--- a/lib/golang/go-query-params.go
+++ b/lib/golang/go-query-params.go
@@ -107,12 +107,9 @@ func {{ .goqctx.ActionName }}QueryFromString(rawQuery string) {{ .goqctx.ActionN
 	return v
 }
 
-
-{{ if .EnabledGin }}
 func {{ .goqctx.ActionName }}QueryFromHttp(r *http.Request) {{ .goqctx.ActionName }}Query {
 	return {{ .goqctx.ActionName }}QueryFromString(r.URL.RawQuery)
 }
-{{ end }}
 
 func (q {{ .goqctx.ActionName }}Query) Values() url.Values {
 	return q.values
diff --git a/lib/js/js-headers.go b/lib/js/js-headers.go
index 77fb1f33..14e776a4 100644
--- a/lib/js/js-headers.go
+++ b/lib/js/js-headers.go
@@ -56,11 +56,6 @@ func renderJsTsCommonHeadersInfo(headerColumns []core.EmiHeader) ([]renderedJsHe
 	return headers, nil
 }
 
-var GEN_NEST_JS_COMPATIBILITY string = "nestjs"
-var GEN_TYPESCRIPT_COMPATIBILITY string = "typescript"
-var GEN_SKIP_ENVELOPES string = "no-envelope"
-var GEN_REACT_COMPATIBILITY string = "react"
-
 func JsHeaderClass(
 	headerctx jsHeaderClassContext,
 	ctx core.MicroGenContext,
diff --git a/lib/js/js-module.go b/lib/js/js-module.go
index cfc151aa..8b90ac90 100644
--- a/lib/js/js-module.go
+++ b/lib/js/js-module.go
@@ -8,7 +8,6 @@ import (
 	"embed"
 	"os"
 	"os/exec"
-	"path"
 	"path/filepath"
 	"slices"
 	"strings"
@@ -199,17 +198,15 @@ func JsModuleFullVirtualFiles(module *core.Emi, ctx core.MicroGenContext) ([]cor
 		dtos = append(dtos, actionRendered)
 	}
 
-	internalUsage := []string{}
 	// Those actions are valid ts or js files, including some helpers for react, fetch
 	// and couple of more, directly can be written on the disk
 	for _, action := range actionsRendered {
 
 		for _, loc := range action.CodeChunkDependensies {
 			if strings.Contains(loc.Location, getSdkAwareLocation(ctx, INTERNAL_SDK_JS_LOCATION, "")) || strings.Contains(loc.Location, getSdkAwareLocation(ctx, INTERNAL_SDK_REACT_LOCATION, "")) {
-
-				internalUsage = append(internalUsage, loc.Location)
 				continue
 			}
+
 			globalPacakges = append(globalPacakges, loc.Location)
 		}
 
@@ -223,7 +220,6 @@ func JsModuleFullVirtualFiles(module *core.Emi, ctx core.MicroGenContext) ([]cor
 	for _, dtoItem := range dtos {
 		for _, loc := range dtoItem.CodeChunkDependensies {
 			if strings.Contains(loc.Location, getSdkAwareLocation(ctx, INTERNAL_SDK_JS_LOCATION, "")) || strings.Contains(loc.Location, getSdkAwareLocation(ctx, INTERNAL_SDK_REACT_LOCATION, "")) {
-				internalUsage = append(internalUsage, loc.Location)
 				continue
 			}
 			globalPacakges = append(globalPacakges, loc.Location)
@@ -236,18 +232,40 @@ func JsModuleFullVirtualFiles(module *core.Emi, ctx core.MicroGenContext) ([]cor
 		})
 	}
 
-	// Let's add a package.json :)
-	pkg, err := GeneratePackageJSON("sdk", globalPacakges, ctx)
-	if err != nil {
-		return nil, err
+	skipPackage := strings.Contains(ctx.Tags, GEN_SKIP_PACKAGE_JSON)
+
+	if !skipPackage {
+		// Let's add a package.json :)
+		pkg, err := GeneratePackageJSON("sdk", globalPacakges, ctx)
+		if err != nil {
+			return nil, err
+		}
+
+		files = append(files, core.VirtualFile{
+			Name:         "package.json",
+			Extension:    "",
+			ActualScript: string(pkg),
+		})
 	}
 
-	files = append(files, core.VirtualFile{
-		Name:         "package.json",
-		Extension:    "",
-		ActualScript: string(pkg),
-	})
+	// If user passed no-sdk as a tag, we do not add it at all.
+	skipSDK := strings.Contains(ctx.Tags, GEN_SKIP_SDK)
+	if !skipSDK {
 
+		if sdkFiles, err := JsGetTargetSdkFiles(ctx); err != nil {
+			return files, nil
+		} else {
+			files = append(files, sdkFiles...)
+		}
+	}
+
+	return files, nil
+}
+
+// Prints whatever sdk files it has into a directory, regardless of the usage.
+// Useful when you want to build a single place for sdks, and change the import path
+func JsGetTargetSdkFiles(ctx core.MicroGenContext) ([]core.VirtualFile, error) {
+	sdkFiles := []core.VirtualFile{}
 	isTypeScript := strings.Contains(ctx.Tags, GEN_TYPESCRIPT_COMPATIBILITY)
 	skipEnvelopes := strings.Contains(ctx.Tags, GEN_SKIP_ENVELOPES)
 
@@ -260,24 +278,18 @@ func JsModuleFullVirtualFiles(module *core.Emi, ctx core.MicroGenContext) ([]cor
 			source = &js_envelopes.Content
 		}
 
-		files = append(files, core.FsEmbedToVirtualFile(source, "sdk/envelopes")...)
+		sdkFiles = append(sdkFiles, core.FsEmbedToVirtualFile(source, "sdk/envelopes")...)
 	}
 
-	sdkFiles := []core.VirtualFile{}
 	if isTypeScript {
 		sdkFiles = append(sdkFiles, core.FsEmbedToVirtualFile(&tssdk.Content, "sdk")...)
 	} else {
 		sdkFiles = append(sdkFiles, core.FsEmbedToVirtualFile(&jssdk.Content, "sdk")...)
 	}
 
+	files := []core.VirtualFile{}
 	for _, sdkFile := range sdkFiles {
-		actual := "./" + path.Join(sdkFile.Location, sdkFile.Name, sdkFile.Extension)
-		actual = strings.ReplaceAll(actual, ".ts", "")
-		actual = strings.ReplaceAll(actual, ".js", "")
-
-		if slices.Contains(internalUsage, actual) {
-			files = append(files, sdkFile)
-		}
+		files = append(files, sdkFile)
 	}
 
 	return files, nil
diff --git a/lib/js/js-public-api.go b/lib/js/js-public-api.go
index ede0c78b..fbc7ccbc 100644
--- a/lib/js/js-public-api.go
+++ b/lib/js/js-public-api.go
@@ -142,6 +142,17 @@ func GetJsPublicActions() core.PublicAPIActions {
 				return nil, errors.New("we did not find any matching type for this catalog. set emi: dto, emi: module, etc. type: " + type_)
 			},
 		},
+		{
+			BaseAction: core.BaseAction{
+				Name:             "js:sdk",
+				Description:      "Get's the javascript or typescript (--tags typescript) sdk folder content and writes them in output",
+				WasmFunctionName: "jsGenSdk",
+				Flags:            []core.FlagDef{},
+			},
+			Run: func(ctx core.MicroGenContext) ([]core.VirtualFile, error) {
+				return JsGetTargetSdkFiles(ctx)
+			},
+		},
 		{
 			BaseAction: core.BaseAction{
 				Name:             "js:module",
diff --git a/lib/js/js-sdk/common/WebSocketWasm.js b/lib/js/js-sdk/common/WebSocketWasm.js
new file mode 100644
index 00000000..e8cb215e
--- /dev/null
+++ b/lib/js/js-sdk/common/WebSocketWasm.js
@@ -0,0 +1,95 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+export class WebSocketWasm extends EventTarget {
+    constructor(url, _protocols) {
+        super();
+        this.url = url;
+        this.readyState = WebSocketWasm.CONNECTING;
+        this.onopen = null;
+        this.onmessage = null;
+        this.onerror = null;
+        this.onclose = null;
+        this._id = -1;
+        const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+        const path = u.pathname;
+        const query = u.search.replace(/^\?/, "");
+        // Defer so listeners attached right after `new` still catch 'open', exactly
+        // like the native async connect.
+        queueMicrotask(() => this._open(path, query));
+    }
+    _open(path, query) {
+        var _a;
+        const onMessage = (data) => {
+            var _a;
+            const ev = new MessageEvent("message", { data });
+            (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, ev);
+            this.dispatchEvent(ev);
+        };
+        const onClose = (reason) => {
+            var _a;
+            if (this.readyState === WebSocketWasm.CLOSED)
+                return;
+            this.readyState = WebSocketWasm.CLOSED;
+            const ev = new CloseEvent("close", {
+                reason,
+                code: 1000,
+                wasClean: true,
+            });
+            (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this, ev);
+            this.dispatchEvent(ev);
+        };
+        if (typeof window.wasmWsOpen !== "function") {
+            return this._fail("reactor not ready (window.wasmWsOpen missing)");
+        }
+        this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+        if (this._id < 0) {
+            return this._fail(`no reactive handler registered for "${path}"`);
+        }
+        this.readyState = WebSocketWasm.OPEN;
+        const ev = new Event("open");
+        (_a = this.onopen) === null || _a === void 0 ? void 0 : _a.call(this, ev);
+        this.dispatchEvent(ev);
+    }
+    _fail(message) {
+        var _a, _b;
+        this.readyState = WebSocketWasm.CLOSED;
+        const err = new Event("error");
+        err.message = message;
+        (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err);
+        this.dispatchEvent(err);
+        const close = new CloseEvent("close", {
+            reason: message,
+            code: 1006,
+            wasClean: false,
+        });
+        (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this, close);
+        this.dispatchEvent(close);
+    }
+    send(data) {
+        if (this.readyState !== WebSocketWasm.OPEN) {
+            throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+        }
+        // Strings pass through; everything else is stringified for now. Real binary
+        // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+        window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+    }
+    close(_code, _reason) {
+        if (this.readyState === WebSocketWasm.CLOSING ||
+            this.readyState === WebSocketWasm.CLOSED) {
+            return;
+        }
+        this.readyState = WebSocketWasm.CLOSING;
+        if (this._id >= 0)
+            window.wasmWsClose(this._id);
+    }
+}
+WebSocketWasm.CONNECTING = 0;
+WebSocketWasm.OPEN = 1;
+WebSocketWasm.CLOSING = 2;
+WebSocketWasm.CLOSED = 3;
diff --git a/lib/js/js-sdk/common/WebSocketX.js b/lib/js/js-sdk/common/WebSocketX.js
index f3601233..3dd0a7d4 100644
--- a/lib/js/js-sdk/common/WebSocketX.js
+++ b/lib/js/js-sdk/common/WebSocketX.js
@@ -37,13 +37,17 @@ export class WebSocketX extends WebSocket {
             data instanceof Blob ||
             data instanceof ArrayBuffer ||
             ArrayBuffer.isView(data)) {
+            // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+            // parameterizes BufferSource as ArrayBufferView, so the
+            // ArrayBufferLike-backed view from isView() needs widening on forward.
             super.send(data);
         }
         else if (data !== undefined && data !== null) {
             super.send(data.toString());
         }
     }
-    // implementation
+    // implementation (signature is not part of the public overload set, so it is
+    // widened to encompass the overloads above under strictFunctionTypes)
     addEventListener(type, listener, options) {
         if (type === "message") {
             const wrapped = ((ev) => {
diff --git a/lib/js/js-static-websocket-create.go b/lib/js/js-static-websocket-create.go
index af9042b2..985d36e2 100644
--- a/lib/js/js-static-websocket-create.go
+++ b/lib/js/js-static-websocket-create.go
@@ -74,6 +74,7 @@ func CreateWebSocketStaticHelper(fetchctx fetchStaticFunctionContext, ctx core.M
 		{{ if .hasQueryParams }}
 			|@query.params|,
 		{{ end }}
+		options
 	) => {
 		const url = overrideUrl ?? {{  .fetchctx.UrlCreatorFunction -}}(
 			{{ if .hasQueryParams }}
@@ -81,15 +82,11 @@ func CreateWebSocketStaticHelper(fetchctx fetchStaticFunctionContext, ctx core.M
 			{{ end }}
 			qs
 		)
-			
-		return new WebSocketX|@generic|(
-			url,
-			undefined,
-			{
-				MessageFactoryClass: |@MessageFactoryClass|,
-			}
-		);
 
+		const Cls = options?.SocketClass ? options.SocketClass : WebSocketX|@generic|;
+		return new Cls(url, undefined, {
+			MessageFactoryClass: |@MessageFactoryClass|,
+		});
 	}
 	`
 
diff --git a/lib/js/js-tags.go b/lib/js/js-tags.go
new file mode 100644
index 00000000..3e2c3d19
--- /dev/null
+++ b/lib/js/js-tags.go
@@ -0,0 +1,9 @@
+package js
+
+// List of tags that you can pass to the compiler in javascript.
+var GEN_NEST_JS_COMPATIBILITY string = "nestjs"
+var GEN_TYPESCRIPT_COMPATIBILITY string = "typescript"
+var GEN_SKIP_PACKAGE_JSON string = "no-package"
+var GEN_SKIP_ENVELOPES string = "no-envelope"
+var GEN_SKIP_SDK string = "no-sdk"
+var GEN_REACT_COMPATIBILITY string = "react"
diff --git a/lib/js/ts-sdk/common/WebSocketWasm.ts b/lib/js/ts-sdk/common/WebSocketWasm.ts
new file mode 100644
index 00000000..b4b63e1e
--- /dev/null
+++ b/lib/js/ts-sdk/common/WebSocketWasm.ts
@@ -0,0 +1,125 @@
+// WebSocketWasm — a drop-in replacement for the native WebSocket, backed by the
+// Go-WASM reactor (emigo.WasmReactor). Swap `new WebSocket(url)` for
+// `new WebSocketWasm(url)` and the rest of your code is identical: readyState,
+// onopen/onmessage/onclose/onerror, addEventListener, send(), close().
+//
+// It is NOT a network client — there is no handshake and no socket. The
+// constructor's URL is only used for its pathname (to pick the reactor handler)
+// and query string; the host is ignored.
+
+// The Go-WASM reactor installs these globals on `window`. Declare them so the
+// bridge calls below type-check.
+declare global {
+  interface Window {
+    wasmWsOpen?: (
+      path: string,
+      query: string,
+      onMessage: (data: string) => void,
+      onClose: (reason: string) => void,
+    ) => number;
+    wasmWsSend: (id: number, data: string) => void;
+    wasmWsClose: (id: number) => void;
+  }
+}
+
+export class WebSocketWasm extends EventTarget {
+  static readonly CONNECTING = 0;
+  static readonly OPEN = 1;
+  static readonly CLOSING = 2;
+  static readonly CLOSED = 3;
+
+  url: string;
+  readyState: number;
+  onopen: ((ev: Event) => void) | null;
+  onmessage: ((ev: MessageEvent) => void) | null;
+  onerror: ((ev: Event) => void) | null;
+  onclose: ((ev: CloseEvent) => void) | null;
+  private _id: number;
+
+  constructor(url: string, _protocols?: string | string[]) {
+    super();
+    this.url = url;
+    this.readyState = WebSocketWasm.CONNECTING;
+    this.onopen = null;
+    this.onmessage = null;
+    this.onerror = null;
+    this.onclose = null;
+    this._id = -1;
+
+    const u = new URL(url, "ws://wasm.local"); // base lets bare paths parse
+    const path = u.pathname;
+    const query = u.search.replace(/^\?/, "");
+
+    // Defer so listeners attached right after `new` still catch 'open', exactly
+    // like the native async connect.
+    queueMicrotask(() => this._open(path, query));
+  }
+
+  private _open(path: string, query: string): void {
+    const onMessage = (data: string): void => {
+      const ev = new MessageEvent("message", { data });
+      this.onmessage?.(ev);
+      this.dispatchEvent(ev);
+    };
+    const onClose = (reason: string): void => {
+      if (this.readyState === WebSocketWasm.CLOSED) return;
+      this.readyState = WebSocketWasm.CLOSED;
+      const ev = new CloseEvent("close", {
+        reason,
+        code: 1000,
+        wasClean: true,
+      });
+      this.onclose?.(ev);
+      this.dispatchEvent(ev);
+    };
+
+    if (typeof window.wasmWsOpen !== "function") {
+      return this._fail("reactor not ready (window.wasmWsOpen missing)");
+    }
+
+    this._id = window.wasmWsOpen(path, query, onMessage, onClose);
+    if (this._id < 0) {
+      return this._fail(`no reactive handler registered for "${path}"`);
+    }
+
+    this.readyState = WebSocketWasm.OPEN;
+    const ev = new Event("open");
+    this.onopen?.(ev);
+    this.dispatchEvent(ev);
+  }
+
+  private _fail(message: string): void {
+    this.readyState = WebSocketWasm.CLOSED;
+    const err: Event & { message?: string } = new Event("error");
+    err.message = message;
+    this.onerror?.(err);
+    this.dispatchEvent(err);
+    const close = new CloseEvent("close", {
+      reason: message,
+      code: 1006,
+      wasClean: false,
+    });
+    this.onclose?.(close);
+    this.dispatchEvent(close);
+  }
+
+  send(data: unknown): void {
+    if (this.readyState !== WebSocketWasm.OPEN) {
+      throw new DOMException("WebSocketWasm is not open", "InvalidStateError");
+    }
+    // Strings pass through; everything else is stringified for now. Real binary
+    // (ArrayBuffer/Blob) would carry a type flag across the bridge — future work.
+    window.wasmWsSend(this._id, typeof data === "string" ? data : String(data));
+  }
+
+  close(_code?: number, _reason?: string): void {
+    if (
+      this.readyState === WebSocketWasm.CLOSING ||
+      this.readyState === WebSocketWasm.CLOSED
+    ) {
+      return;
+    }
+    this.readyState = WebSocketWasm.CLOSING;
+    if (this._id >= 0) window.wasmWsClose(this._id);
+  }
+}
diff --git a/lib/js/ts-sdk/common/WebSocketX.ts b/lib/js/ts-sdk/common/WebSocketX.ts
index cb1d758f..a8fdf3d9 100644
--- a/lib/js/ts-sdk/common/WebSocketX.ts
+++ b/lib/js/ts-sdk/common/WebSocketX.ts
@@ -47,7 +47,10 @@ export class WebSocketX<
       data instanceof ArrayBuffer ||
       ArrayBuffer.isView(data)
     ) {
-      super.send(data);
+      // Cast to whatever the runtime's WebSocket.send accepts: newer lib.dom
+      // parameterizes BufferSource as ArrayBufferView, so the
+      // ArrayBufferLike-backed view from isView() needs widening on forward.
+      super.send(data as Parameters[0]);
     } else if (data !== undefined && data !== null) {
       super.send(data.toString());
     }
@@ -66,10 +69,11 @@ export class WebSocketX<
     options?: boolean | AddEventListenerOptions
   ): void;
 
-  // implementation
+  // implementation (signature is not part of the public overload set, so it is
+  // widened to encompass the overloads above under strictFunctionTypes)
   addEventListener(
     type: string,
-    listener: EventListenerOrEventListenerObject,
+    listener: EventListenerOrEventListenerObject | ((this: WebSocket, ev: any) => unknown),
     options?: boolean | AddEventListenerOptions
   ): void {
     if (type === "message") {
diff --git a/lib/kotlin/kotlin-public-api.go b/lib/kotlin/kotlin-public-api.go
index 72a21ab6..1fe37db9 100644
--- a/lib/kotlin/kotlin-public-api.go
+++ b/lib/kotlin/kotlin-public-api.go
@@ -207,29 +207,28 @@ func AsFullDocument(x *core.CodeChunkCompiled, packageName string) string {
 	finalContent = string(core.EscapeLines([]byte(finalContent)))
 	return finalContent
 }
+
 func CombineJavaImport(chunk core.CodeChunkCompiled) string {
 	statements := map[string]struct{}{}
 
-	// Collect unique import statements
 	for _, dep := range chunk.CodeChunkDependensies {
 		statement := ""
 		if len(dep.Objects) > 0 {
 			statement = fmt.Sprintf(`%v "%v" //x`, dep.Objects[0], dep.Location)
 		} else {
-			statement = fmt.Sprintf(`%v`, dep.Location)
+			statement = dep.Location
 		}
 		statements[statement] = struct{}{}
 	}
 
-	// Sort statements for deterministic output
 	var sorted []string
 	for stmt := range statements {
 		sorted = append(sorted, stmt)
 	}
 	sort.Strings(sorted)
 
-	statementsX := []string{}
-	for v := range statements {
+	statementsX := make([]string, 0, len(sorted))
+	for _, v := range sorted {
 		statementsX = append(statementsX, fmt.Sprintf("import %v", v))
 	}
 

From 10a36eaa5fd445af3077b1ef777ef1880acfbdb1 Mon Sep 17 00:00:00 2001
From: Ali 
Date: Tue, 2 Jun 2026 18:05:52 +0200
Subject: [PATCH 2/2] Update deploy.yml

---
 .github/workflows/deploy.yml | 2 --
 1 file changed, 2 deletions(-)

diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index f7cdf92a..d6bee0e3 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -63,8 +63,6 @@ jobs:
       - name: Regenerate allegro
         run: cd ./examples/allegro-sdk && make
       
-      - name: Check swift
-        run: make check_swift
 
       - name: Add web version and playground into same
         run: make compile-github