@umituz/web-ai 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{AIErrors-B2ogd1PB.d.ts → AIErrors-CLjXRty-.d.ts} +99 -92
  2. package/dist/{AIErrors-C5EasV_c.d.cts → AIErrors-DjZXUiLT.d.cts} +99 -92
  3. package/dist/PromptBuilder-B5Lm1znm.d.ts +215 -0
  4. package/dist/PromptBuilder-DIUZlfV6.d.cts +215 -0
  5. package/dist/{text-generation.service-BQO3Tvz2.d.cts → cancellation-error-Cj7fJyCg.d.cts} +66 -3
  6. package/dist/{text-generation.service-CcYQM6Ch.d.ts → cancellation-error-CkMn5Kft.d.ts} +66 -3
  7. package/dist/chat/index.cjs.map +1 -1
  8. package/dist/chat/index.d.cts +3 -3
  9. package/dist/chat/index.d.ts +3 -3
  10. package/dist/chat/index.js.map +1 -1
  11. package/dist/{chat.service-CL1qtYxe.d.cts → chat.service-9M-KpLo-.d.cts} +1 -1
  12. package/dist/{chat.service-q05GnhEm.d.ts → chat.service-B4FLFxR1.d.ts} +1 -1
  13. package/dist/content/index.cjs +1582 -452
  14. package/dist/content/index.cjs.map +1 -1
  15. package/dist/content/index.d.cts +165 -219
  16. package/dist/content/index.d.ts +165 -219
  17. package/dist/content/index.js +1525 -453
  18. package/dist/content/index.js.map +1 -1
  19. package/dist/{create-ai-9PW752z8.d.ts → create-ai-0eZFFqTw.d.ts} +1 -1
  20. package/dist/{create-ai-CXYKPK6G.d.cts → create-ai-BrKR_5fQ.d.cts} +1 -1
  21. package/dist/hooks/index.cjs +924 -31
  22. package/dist/hooks/index.cjs.map +1 -1
  23. package/dist/hooks/index.d.cts +44 -8
  24. package/dist/hooks/index.d.ts +44 -8
  25. package/dist/hooks/index.js +919 -32
  26. package/dist/hooks/index.js.map +1 -1
  27. package/dist/index-BUVULo3h.d.ts +177 -0
  28. package/dist/index-BulSkB2L.d.cts +177 -0
  29. package/dist/index.cjs +3057 -563
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +8 -5
  32. package/dist/index.d.ts +8 -5
  33. package/dist/index.js +3011 -564
  34. package/dist/index.js.map +1 -1
  35. package/dist/{provider.factory-DfDfk0dK.d.ts → provider.factory-BwPnqSEU.d.ts} +3 -1
  36. package/dist/{provider.factory-BxsfK4WW.d.cts → provider.factory-DyfJtR8M.d.cts} +3 -1
  37. package/dist/providers/index.cjs +818 -27
  38. package/dist/providers/index.cjs.map +1 -1
  39. package/dist/providers/index.d.cts +50 -8
  40. package/dist/providers/index.d.ts +50 -8
  41. package/dist/providers/index.js +806 -28
  42. package/dist/providers/index.js.map +1 -1
  43. package/dist/wizard/index.d.cts +2 -86
  44. package/dist/wizard/index.d.ts +2 -86
  45. package/package.json +21 -1
  46. package/dist/ContentGeneration-B6iK2B33.d.cts +0 -93
  47. package/dist/ContentGeneration-B6iK2B33.d.ts +0 -93
@@ -513,6 +513,9 @@ var ProviderFactory = class {
513
513
  );
514
514
  }
515
515
  };
516
+ function createProviderFactory(config) {
517
+ return new ProviderFactory(config);
518
+ }
516
519
 
517
520
  // src/core/constants/protocol.constants.ts
518
521
  var SSE_PREFIX = "data: ";
@@ -2091,6 +2094,9 @@ function toGroqMessages(messages, systemPrompt) {
2091
2094
  }
2092
2095
  return wire;
2093
2096
  }
2097
+ function createGroqProvider(config) {
2098
+ return new GroqProvider(config);
2099
+ }
2094
2100
  function findLastIndex2(items, predicate) {
2095
2101
  for (let i = items.length - 1; i >= 0; i--) {
2096
2102
  if (predicate(items[i])) return i;
@@ -2553,39 +2559,811 @@ function createFalProvider(config) {
2553
2559
  return new FalProvider(config);
2554
2560
  }
2555
2561
 
2556
- // src/providers/pruna/pruna-generate.ts
2557
- var prunaCorePromise = null;
2558
- async function loadPrunaCore() {
2559
- if (!prunaCorePromise) {
2560
- const specifier = "@umituz/pruna-provider/core";
2561
- prunaCorePromise = import(specifier);
2562
+ // src/providers/pruna/client/core/constants/limits.ts
2563
+ var DEFAULT_ASPECT_RATIO = "16:9";
2564
+ var P_VIDEO_DEFAULTS = {
2565
+ duration: 5,
2566
+ resolution: "720p",
2567
+ fps: 24,
2568
+ draft: false,
2569
+ promptUpsampling: true
2570
+ };
2571
+ var POLL_DEFAULTS = {
2572
+ intervalMs: 3e3,
2573
+ maxAttempts: 120,
2574
+ maxIntervalMs: 1e4,
2575
+ backoffBase: 1.5,
2576
+ jitterPercent: 0.1
2577
+ };
2578
+ var DEFAULT_DEDUPLICATOR_TTL_MS = 3e4;
2579
+ var DEDUPLICATOR_CLEANUP_GRACE_MS = 100;
2580
+
2581
+ // src/providers/pruna/client/core/constants/network.ts
2582
+ var HTTPS_PREFIX = "https://";
2583
+ var HTTP_PREFIX = "http://";
2584
+ var BASE64_MARKER = "base64,";
2585
+ var PRUNA_BASE_URL = "https://api.pruna.ai";
2586
+ var PRUNA_PREDICTIONS_URL = `${PRUNA_BASE_URL}/v1/predictions`;
2587
+ var PRUNA_FILES_URL = `${PRUNA_BASE_URL}/v1/files`;
2588
+ var AUTH_FAILURE_STATUSES = [401, 403];
2589
+ var MIN_API_KEY_LENGTH = 1;
2590
+ var MAX_API_KEY_LENGTH = 256;
2591
+
2592
+ // src/providers/pruna/client/core/constants/mime-types.ts
2593
+ var MIME_PNG = "image/png";
2594
+ var MIME_JPEG = "image/jpeg";
2595
+ var MIME_WEBP = "image/webp";
2596
+ var DEFAULT_IMAGE_MIME = MIME_PNG;
2597
+ var MIME_FILE_EXTENSION = {
2598
+ [MIME_PNG]: "png",
2599
+ [MIME_JPEG]: "jpg",
2600
+ [MIME_WEBP]: "webp"
2601
+ };
2602
+ var IMAGE_SIGNATURES = {
2603
+ PNG: [137, 80],
2604
+ JPEG: [255, 216],
2605
+ WEBP_RIFF: [82, 73]
2606
+ };
2607
+
2608
+ // src/providers/pruna/client/core/errors/cancellation-error.ts
2609
+ var CANCELLATION_MESSAGE = "Request cancelled by user";
2610
+ var CancellationError = class extends Error {
2611
+ constructor(message = CANCELLATION_MESSAGE) {
2612
+ super(message);
2613
+ this.name = "CancellationError";
2614
+ }
2615
+ };
2616
+
2617
+ // src/providers/pruna/client/core/errors/authentication-error.ts
2618
+ var AUTHENTICATION_MESSAGE = "Authentication failed. Please check your API key.";
2619
+ var AuthenticationError = class extends Error {
2620
+ constructor(message = AUTHENTICATION_MESSAGE) {
2621
+ super(message);
2622
+ this.name = "AuthenticationError";
2623
+ }
2624
+ };
2625
+
2626
+ // src/providers/pruna/client/core/errors/timeout-error.ts
2627
+ var TIMEOUT_MESSAGE = "Generation timed out. Maximum polling attempts reached.";
2628
+ var TimeoutError = class extends Error {
2629
+ constructor(message = TIMEOUT_MESSAGE) {
2630
+ super(message);
2631
+ this.name = "TimeoutError";
2562
2632
  }
2563
- return prunaCorePromise;
2633
+ };
2634
+
2635
+ // src/providers/pruna/client/core/errors/validation-error.ts
2636
+ var ValidationError = class extends Error {
2637
+ field;
2638
+ reason;
2639
+ receivedValue;
2640
+ constructor(context) {
2641
+ super(`Invalid ${context.field}: ${context.reason}`);
2642
+ this.name = "ValidationError";
2643
+ this.field = context.field;
2644
+ this.reason = context.reason;
2645
+ this.receivedValue = context.receivedValue;
2646
+ }
2647
+ };
2648
+
2649
+ // src/providers/pruna/client/core/utils/base64.ts
2650
+ var globalScope = globalThis;
2651
+ var hasBuffer = typeof globalScope.Buffer?.from === "function";
2652
+ function base64ToBytes(raw) {
2653
+ if (hasBuffer) {
2654
+ const bufferFactory = globalScope.Buffer;
2655
+ if (!bufferFactory) {
2656
+ throw new Error("Buffer unavailable despite detection flag");
2657
+ }
2658
+ const buf = bufferFactory.from(raw, "base64");
2659
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
2660
+ }
2661
+ const decoded = atob(raw);
2662
+ return Uint8Array.from(decoded, (char) => char.charCodeAt(0));
2564
2663
  }
2565
- async function* generateWithPruna(request, apiKey, signal, onProgress) {
2566
- const prunaCore = await loadPrunaCore();
2567
- if (prunaCore.generateWithPruna) {
2568
- yield* prunaCore.generateWithPruna(request, apiKey, signal, onProgress);
2569
- return;
2570
- }
2571
- if (!prunaCore.submitPrediction || !prunaCore.pollForResult) {
2572
- throw new Error("@umituz/pruna-provider/core does not export required functions");
2573
- }
2574
- const modelId = request.model || (request.image ? "p-image-edit" : "p-image");
2575
- const prediction = await prunaCore.submitPrediction(modelId, request, apiKey, signal, onProgress);
2576
- if (prediction.output && typeof prediction.output === "object" && "url" in prediction.output) {
2577
- yield {
2578
- stage: "predicting",
2579
- result: { url: prediction.output.url, model: modelId }
2664
+
2665
+ // src/providers/pruna/client/core/utils/mime-detector.ts
2666
+ var MIN_SIGNATURE_BYTES = 2;
2667
+ function matchesSignature(bytes, signature) {
2668
+ if (bytes.length < signature.length) return false;
2669
+ return signature.every((value, index) => bytes[index] === value);
2670
+ }
2671
+ function detectImageMime(bytes) {
2672
+ if (bytes.length < MIN_SIGNATURE_BYTES) return DEFAULT_IMAGE_MIME;
2673
+ if (matchesSignature(bytes, IMAGE_SIGNATURES.PNG)) return MIME_PNG;
2674
+ if (matchesSignature(bytes, IMAGE_SIGNATURES.JPEG)) return MIME_JPEG;
2675
+ if (matchesSignature(bytes, IMAGE_SIGNATURES.WEBP_RIFF)) return MIME_WEBP;
2676
+ return DEFAULT_IMAGE_MIME;
2677
+ }
2678
+
2679
+ // src/providers/pruna/client/core/utils/api-error-parser.ts
2680
+ async function parseApiError(response, fallback) {
2681
+ const payload = await response.json().catch(() => ({ message: response.statusText }));
2682
+ const message = payload.message ?? `${fallback}: ${response.status}`;
2683
+ const error = new Error(message);
2684
+ error.statusCode = response.status;
2685
+ return error;
2686
+ }
2687
+
2688
+ // src/providers/pruna/client/core/protocol/http-status.ts
2689
+ function isAuthFailureStatus(status) {
2690
+ return AUTH_FAILURE_STATUSES.includes(status);
2691
+ }
2692
+
2693
+ // src/providers/pruna/client/core/protocol/job-status.ts
2694
+ var TERMINAL_SUCCESS_STATUSES = ["succeeded", "completed"];
2695
+ var TERMINAL_FAILURE_STATUSES = ["failed"];
2696
+ function isTerminalSuccessStatus(status) {
2697
+ if (!status) return false;
2698
+ return TERMINAL_SUCCESS_STATUSES.includes(status);
2699
+ }
2700
+ function isTerminalFailureStatus(status) {
2701
+ if (!status) return false;
2702
+ return TERMINAL_FAILURE_STATUSES.includes(status);
2703
+ }
2704
+
2705
+ // src/providers/pruna/client/core/protocol/abort-signal-classifier.ts
2706
+ function isAbortError(err) {
2707
+ if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true;
2708
+ if (err instanceof Error && err.name === "AbortError") return true;
2709
+ return false;
2710
+ }
2711
+
2712
+ // src/providers/pruna/client/core/protocol/pruna-url-builder.ts
2713
+ function isAbsoluteHttpUrl(value) {
2714
+ return value.startsWith(HTTPS_PREFIX) || value.startsWith(HTTP_PREFIX);
2715
+ }
2716
+ function isHttpsUrl(value) {
2717
+ return value.startsWith(HTTPS_PREFIX);
2718
+ }
2719
+ function buildPrunaApiUrl(pathOrUrl) {
2720
+ if (isAbsoluteHttpUrl(pathOrUrl)) return pathOrUrl;
2721
+ return `${PRUNA_BASE_URL}${pathOrUrl}`;
2722
+ }
2723
+ function buildFileUrlById(fileId) {
2724
+ return `${PRUNA_FILES_URL}/${fileId}`;
2725
+ }
2726
+
2727
+ // src/providers/pruna/client/core/math/exponential-backoff.ts
2728
+ function calculateExponentialBackoff2(inputs) {
2729
+ const {
2730
+ attempt,
2731
+ baseIntervalMs,
2732
+ maxIntervalMs = POLL_DEFAULTS.maxIntervalMs,
2733
+ jitterPercent = POLL_DEFAULTS.jitterPercent,
2734
+ growthBase = POLL_DEFAULTS.backoffBase
2735
+ } = inputs;
2736
+ const safeAttempt = Math.max(0, attempt);
2737
+ const safeBase = Math.max(0, baseIntervalMs);
2738
+ const exponentialDelay = Math.min(safeBase * Math.pow(growthBase, safeAttempt), maxIntervalMs);
2739
+ const jitter = exponentialDelay * jitterPercent * Math.random();
2740
+ return exponentialDelay + jitter;
2741
+ }
2742
+
2743
+ // src/providers/pruna/client/core/utils/uri-resolver.ts
2744
+ var uriCache = /* @__PURE__ */ new WeakMap();
2745
+ function stripBase64Prefix(image) {
2746
+ if (isHttpsUrl(image)) return image;
2747
+ const base64Index = image.indexOf(BASE64_MARKER);
2748
+ return base64Index !== -1 ? image.slice(base64Index + BASE64_MARKER.length) : image;
2749
+ }
2750
+ function readOutput(output) {
2751
+ if (typeof output === "string") return output;
2752
+ if (Array.isArray(output) && output.length > 0) return output[0] ?? null;
2753
+ if (output !== null && typeof output === "object" && "url" in output) {
2754
+ return output.url;
2755
+ }
2756
+ return null;
2757
+ }
2758
+ function extractUri(data) {
2759
+ const cached = uriCache.get(data);
2760
+ if (cached !== void 0) return cached;
2761
+ if (!isTerminalSuccessStatus(data.status)) {
2762
+ uriCache.set(data, null);
2763
+ return null;
2764
+ }
2765
+ const result = data.generation_url ?? readOutput(data.output) ?? data.video_url ?? data.data ?? null;
2766
+ uriCache.set(data, result);
2767
+ return result;
2768
+ }
2769
+ function resolveUri(uri) {
2770
+ return uri.startsWith("/") ? `${PRUNA_BASE_URL}${uri}` : uri;
2771
+ }
2772
+
2773
+ // src/providers/pruna/client/core/services/pruna-client.service.ts
2774
+ function buildFileExtension(mime) {
2775
+ return MIME_FILE_EXTENSION[mime] ?? "bin";
2776
+ }
2777
+ async function uploadImage(base64OrUrl, apiKey, onProgress) {
2778
+ if (isHttpsUrl(base64OrUrl)) return base64OrUrl;
2779
+ if (base64OrUrl.startsWith(HTTP_PREFIX)) {
2780
+ throw new Error("Only HTTPS URLs are supported for security.");
2781
+ }
2782
+ onProgress?.("uploading");
2783
+ const raw = stripBase64Prefix(base64OrUrl);
2784
+ let bytes;
2785
+ try {
2786
+ bytes = base64ToBytes(raw);
2787
+ } catch {
2788
+ throw new Error("Invalid image format. Provide base64 or a valid HTTPS URL.");
2789
+ }
2790
+ const mime = detectImageMime(bytes);
2791
+ const buffer = bytes.buffer.slice(
2792
+ bytes.byteOffset,
2793
+ bytes.byteOffset + bytes.byteLength
2794
+ );
2795
+ const blob = new Blob([buffer], { type: mime });
2796
+ const formData = new FormData();
2797
+ formData.append("content", blob, `upload.${buildFileExtension(mime)}`);
2798
+ const res = await fetch(PRUNA_FILES_URL, {
2799
+ method: "POST",
2800
+ headers: { apikey: apiKey },
2801
+ body: formData
2802
+ });
2803
+ if (!res.ok) {
2804
+ throw await parseApiError(res, "File upload error");
2805
+ }
2806
+ const data = await res.json();
2807
+ return data.urls?.get ?? buildFileUrlById(data.id ?? "");
2808
+ }
2809
+ async function submitPrediction(model, input, apiKey, signal, onProgress) {
2810
+ onProgress?.("predicting");
2811
+ const res = await fetch(PRUNA_PREDICTIONS_URL, {
2812
+ method: "POST",
2813
+ headers: {
2814
+ apikey: apiKey,
2815
+ Model: model,
2816
+ "Try-Sync": "true",
2817
+ "Content-Type": "application/json"
2818
+ },
2819
+ body: JSON.stringify({ input }),
2820
+ signal
2821
+ });
2822
+ if (!res.ok) {
2823
+ throw await parseApiError(res, "API error");
2824
+ }
2825
+ return res.json();
2826
+ }
2827
+ var GenerationFailedError = class extends Error {
2828
+ constructor(message) {
2829
+ super(message);
2830
+ this.name = "GenerationFailedError";
2831
+ }
2832
+ };
2833
+ async function attemptPoll(fullUrl, apiKey, signal) {
2834
+ let res;
2835
+ try {
2836
+ res = await fetch(fullUrl, { headers: { apikey: apiKey }, signal });
2837
+ } catch (err) {
2838
+ if (isAbortError(err)) throw new CancellationError();
2839
+ return { outcome: "transient-failure" };
2840
+ }
2841
+ if (!res.ok) {
2842
+ if (isAuthFailureStatus(res.status)) throw new AuthenticationError();
2843
+ return { outcome: "transient-failure" };
2844
+ }
2845
+ let data;
2846
+ try {
2847
+ data = await res.json();
2848
+ } catch {
2849
+ return { outcome: "transient-failure" };
2850
+ }
2851
+ if (isTerminalSuccessStatus(data.status)) {
2852
+ const uri = extractUri(data);
2853
+ if (uri) return { outcome: "succeeded", uri: resolveUri(uri) };
2854
+ return { outcome: "transient-failure" };
2855
+ }
2856
+ if (isTerminalFailureStatus(data.status)) {
2857
+ throw new GenerationFailedError(data.error ?? "Generation failed during processing.");
2858
+ }
2859
+ return { outcome: "continue" };
2860
+ }
2861
+ async function pollForResult(pollUrl, apiKey, maxAttempts = POLL_DEFAULTS.maxAttempts, intervalMs = POLL_DEFAULTS.intervalMs, signal, onProgress) {
2862
+ const fullUrl = isAbsoluteHttpUrl(pollUrl) ? pollUrl : buildPrunaApiUrl(pollUrl);
2863
+ const controller = new AbortController();
2864
+ const onExternalAbort = () => controller.abort();
2865
+ signal?.addEventListener("abort", onExternalAbort);
2866
+ try {
2867
+ for (let i = 0; i < maxAttempts; i++) {
2868
+ if (signal?.aborted) throw new CancellationError();
2869
+ const delay = calculateExponentialBackoff2({ attempt: i, baseIntervalMs: intervalMs });
2870
+ await new Promise((resolve) => setTimeout(resolve, delay));
2871
+ if (signal?.aborted) throw new CancellationError();
2872
+ onProgress?.("polling", i + 1);
2873
+ const result = await attemptPoll(fullUrl, apiKey, controller.signal);
2874
+ if (result.outcome === "succeeded" && result.uri) {
2875
+ return result.uri;
2876
+ }
2877
+ }
2878
+ throw new TimeoutError();
2879
+ } finally {
2880
+ signal?.removeEventListener("abort", onExternalAbort);
2881
+ controller.abort();
2882
+ }
2883
+ }
2884
+
2885
+ // src/providers/pruna/client/core/math/comparison-hash.ts
2886
+ function sortKeysDeep(value) {
2887
+ if (Array.isArray(value)) {
2888
+ return value.map(sortKeysDeep);
2889
+ }
2890
+ if (value !== null && typeof value === "object") {
2891
+ const record = value;
2892
+ return Object.keys(record).sort().reduce((acc, key) => {
2893
+ acc[key] = sortKeysDeep(record[key]);
2894
+ return acc;
2895
+ }, {});
2896
+ }
2897
+ return value;
2898
+ }
2899
+ function hashValue(value) {
2900
+ if (value === null || typeof value !== "object") {
2901
+ return String(value);
2902
+ }
2903
+ try {
2904
+ return JSON.stringify(sortKeysDeep(value));
2905
+ } catch {
2906
+ return String(value);
2907
+ }
2908
+ }
2909
+ function compositeHash(...values) {
2910
+ return values.map(hashValue).join("|");
2911
+ }
2912
+
2913
+ // src/providers/pruna/client/core/math/cache-key-derivation.ts
2914
+ function deriveGenerationCacheKey(apiKey, input) {
2915
+ return `${apiKey}:${compositeHash(input)}`;
2916
+ }
2917
+
2918
+ // src/providers/pruna/client/core/validation/api-key-validator.ts
2919
+ function assertValidApiKey(apiKey) {
2920
+ if (typeof apiKey !== "string") {
2921
+ throw new ValidationError({
2922
+ field: "apiKey",
2923
+ reason: "must be a string",
2924
+ receivedValue: typeof apiKey
2925
+ });
2926
+ }
2927
+ if (apiKey.length < MIN_API_KEY_LENGTH) {
2928
+ throw new ValidationError({
2929
+ field: "apiKey",
2930
+ reason: "must not be empty",
2931
+ receivedValue: apiKey
2932
+ });
2933
+ }
2934
+ if (apiKey.length > MAX_API_KEY_LENGTH) {
2935
+ throw new ValidationError({
2936
+ field: "apiKey",
2937
+ reason: `exceeds maximum length of ${MAX_API_KEY_LENGTH}`,
2938
+ receivedValue: apiKey.length
2939
+ });
2940
+ }
2941
+ }
2942
+
2943
+ // src/providers/pruna/client/core/validation/image-source-validator.ts
2944
+ function classifyImageSource(source) {
2945
+ if (source.startsWith(HTTPS_PREFIX)) return "https-url";
2946
+ if (source.startsWith(HTTP_PREFIX)) return "http-url";
2947
+ if (source.includes(BASE64_MARKER) || /^[A-Za-z0-9+/=]+$/.test(source)) return "base64";
2948
+ return "unknown";
2949
+ }
2950
+ function assertSecureImageSource(image, fieldName = "image") {
2951
+ if (typeof image !== "string") {
2952
+ throw new ValidationError({
2953
+ field: fieldName,
2954
+ reason: "must be a string",
2955
+ receivedValue: typeof image
2956
+ });
2957
+ }
2958
+ const kind = classifyImageSource(image);
2959
+ if (kind === "http-url") {
2960
+ throw new ValidationError({
2961
+ field: fieldName,
2962
+ reason: "HTTP URLs are not supported; use HTTPS or a base64 data URI",
2963
+ receivedValue: image
2964
+ });
2965
+ }
2966
+ if (kind === "unknown") {
2967
+ throw new ValidationError({
2968
+ field: fieldName,
2969
+ reason: "must be an HTTPS URL or a base64 data URI",
2970
+ receivedValue: typeof image
2971
+ });
2972
+ }
2973
+ }
2974
+
2975
+ // src/providers/pruna/client/core/validation/aspect-ratio-validator.ts
2976
+ var SUPPORTED_ASPECT_RATIOS = [
2977
+ "16:9",
2978
+ "9:16",
2979
+ "1:1",
2980
+ "4:3",
2981
+ "3:4",
2982
+ "3:2",
2983
+ "2:3"
2984
+ ];
2985
+ function isSupportedAspectRatio(value) {
2986
+ return typeof value === "string" && SUPPORTED_ASPECT_RATIOS.includes(value);
2987
+ }
2988
+ function assertValidAspectRatio(value, fieldName = "aspect_ratio") {
2989
+ if (value === void 0 || value === null) return;
2990
+ if (!isSupportedAspectRatio(value)) {
2991
+ throw new ValidationError({
2992
+ field: fieldName,
2993
+ reason: `must be one of ${SUPPORTED_ASPECT_RATIOS.join(", ")}`,
2994
+ receivedValue: value
2995
+ });
2996
+ }
2997
+ }
2998
+
2999
+ // src/providers/pruna/client/core/validation/resolution-validator.ts
3000
+ var SUPPORTED_RESOLUTIONS = ["720p", "1080p"];
3001
+ function isSupportedResolution(value) {
3002
+ return typeof value === "string" && SUPPORTED_RESOLUTIONS.includes(value);
3003
+ }
3004
+ function assertValidResolution(value, fieldName = "resolution") {
3005
+ if (value === void 0 || value === null) return;
3006
+ if (!isSupportedResolution(value)) {
3007
+ throw new ValidationError({
3008
+ field: fieldName,
3009
+ reason: `must be one of ${SUPPORTED_RESOLUTIONS.join(", ")}`,
3010
+ receivedValue: value
3011
+ });
3012
+ }
3013
+ }
3014
+
3015
+ // src/providers/pruna/client/core/validation/duration-validator.ts
3016
+ var MIN_VIDEO_DURATION_SECONDS = 1;
3017
+ var MAX_VIDEO_DURATION_SECONDS = 30;
3018
+ function isValidDuration(value) {
3019
+ return typeof value === "number" && Number.isFinite(value) && value >= MIN_VIDEO_DURATION_SECONDS && value <= MAX_VIDEO_DURATION_SECONDS && Number.isInteger(value);
3020
+ }
3021
+ function assertValidDuration(value, fieldName = "duration") {
3022
+ if (value === void 0 || value === null) return;
3023
+ if (!isValidDuration(value)) {
3024
+ throw new ValidationError({
3025
+ field: fieldName,
3026
+ reason: `must be an integer between ${MIN_VIDEO_DURATION_SECONDS} and ${MAX_VIDEO_DURATION_SECONDS} seconds`,
3027
+ receivedValue: value
3028
+ });
3029
+ }
3030
+ }
3031
+
3032
+ // src/providers/pruna/client/core/validation/prompt-validator.ts
3033
+ var MIN_PROMPT_LENGTH = 1;
3034
+ var MAX_PROMPT_LENGTH = 4e3;
3035
+ function assertValidPrompt(value, fieldName = "prompt") {
3036
+ if (typeof value !== "string") {
3037
+ throw new ValidationError({
3038
+ field: fieldName,
3039
+ reason: "must be a string",
3040
+ receivedValue: typeof value
3041
+ });
3042
+ }
3043
+ if (value.trim().length < MIN_PROMPT_LENGTH) {
3044
+ throw new ValidationError({
3045
+ field: fieldName,
3046
+ reason: "must not be empty or whitespace-only",
3047
+ receivedValue: value
3048
+ });
3049
+ }
3050
+ if (value.length > MAX_PROMPT_LENGTH) {
3051
+ throw new ValidationError({
3052
+ field: fieldName,
3053
+ reason: `exceeds maximum length of ${MAX_PROMPT_LENGTH} characters`,
3054
+ receivedValue: value.length
3055
+ });
3056
+ }
3057
+ }
3058
+
3059
+ // src/providers/pruna/client/core/validation/seed-validator.ts
3060
+ var MIN_SEED = -2147483648;
3061
+ var MAX_SEED = 2147483647;
3062
+ function isValidSeed(value) {
3063
+ return typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value >= MIN_SEED && value <= MAX_SEED;
3064
+ }
3065
+ function assertValidSeed(value, fieldName = "seed") {
3066
+ if (value === void 0 || value === null) return;
3067
+ if (!isValidSeed(value)) {
3068
+ throw new ValidationError({
3069
+ field: fieldName,
3070
+ reason: `must be an integer in [${MIN_SEED}, ${MAX_SEED}]`,
3071
+ receivedValue: value
3072
+ });
3073
+ }
3074
+ }
3075
+
3076
+ // src/providers/pruna/client/core/protocol/input-type-guard.ts
3077
+ function isTextToImageInput(input) {
3078
+ return input.model === "p-image";
3079
+ }
3080
+ function isImageToImageInput(input) {
3081
+ return input.model === "p-image-edit";
3082
+ }
3083
+ function isImageToVideoInput(input) {
3084
+ return input.model === "p-video";
3085
+ }
3086
+
3087
+ // src/providers/pruna/client/core/utils/request-deduplicator.ts
3088
+ var RequestDeduplicator2 = class {
3089
+ pendingRequests = /* @__PURE__ */ new Map();
3090
+ ttl;
3091
+ constructor(ttl = DEFAULT_DEDUPLICATOR_TTL_MS) {
3092
+ this.ttl = ttl;
3093
+ }
3094
+ execute(key, fn) {
3095
+ const existing = this.pendingRequests.get(key);
3096
+ if (existing) {
3097
+ if (Date.now() - existing.timestamp < this.ttl) {
3098
+ return existing.promise;
3099
+ }
3100
+ this.pendingRequests.delete(key);
3101
+ }
3102
+ const promise = fn().finally(() => {
3103
+ setTimeout(() => {
3104
+ this.pendingRequests.delete(key);
3105
+ }, DEDUPLICATOR_CLEANUP_GRACE_MS);
3106
+ });
3107
+ this.pendingRequests.set(key, { promise, timestamp: Date.now() });
3108
+ return promise;
3109
+ }
3110
+ clear() {
3111
+ this.pendingRequests.clear();
3112
+ }
3113
+ size() {
3114
+ this.purgeExpired();
3115
+ return this.pendingRequests.size;
3116
+ }
3117
+ purgeExpired() {
3118
+ const now = Date.now();
3119
+ for (const [key, value] of this.pendingRequests) {
3120
+ if (now - value.timestamp >= this.ttl) {
3121
+ this.pendingRequests.delete(key);
3122
+ }
3123
+ }
3124
+ }
3125
+ };
3126
+ var globalDeduplicator = new RequestDeduplicator2();
3127
+
3128
+ // src/providers/pruna/client/generation/builders/text-to-image.builder.ts
3129
+ var TextToImageInputBuilder = class {
3130
+ model = "p-image";
3131
+ build(input, _context) {
3132
+ const payload = {
3133
+ prompt: input.prompt,
3134
+ aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO
2580
3135
  };
2581
- return;
3136
+ if (input.seed !== void 0) {
3137
+ payload.seed = input.seed;
3138
+ }
3139
+ return Promise.resolve(payload);
2582
3140
  }
2583
- const pollUrl = prediction.status_url || prediction.generation_url;
3141
+ };
3142
+
3143
+ // src/providers/pruna/client/generation/builders/image-to-image.builder.ts
3144
+ var ImageToImageInputBuilder = class {
3145
+ model = "p-image-edit";
3146
+ build(input, _context) {
3147
+ const payload = {
3148
+ images: [stripBase64Prefix(input.image)],
3149
+ prompt: input.prompt,
3150
+ aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO
3151
+ };
3152
+ if (input.seed !== void 0) {
3153
+ payload.seed = input.seed;
3154
+ }
3155
+ return Promise.resolve(payload);
3156
+ }
3157
+ };
3158
+
3159
+ // src/providers/pruna/client/generation/builders/image-to-video.builder.ts
3160
+ var ImageToVideoInputBuilder = class {
3161
+ model = "p-video";
3162
+ async build(input, context) {
3163
+ if (context.signal?.aborted) {
3164
+ throw new CancellationError();
3165
+ }
3166
+ const fileUrl = await uploadImage(
3167
+ input.image,
3168
+ context.apiKey,
3169
+ context.onProgress
3170
+ );
3171
+ return {
3172
+ image: fileUrl,
3173
+ prompt: input.prompt,
3174
+ duration: input.duration ?? P_VIDEO_DEFAULTS.duration,
3175
+ resolution: input.resolution ?? P_VIDEO_DEFAULTS.resolution,
3176
+ fps: P_VIDEO_DEFAULTS.fps,
3177
+ draft: input.draft ?? P_VIDEO_DEFAULTS.draft,
3178
+ aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO,
3179
+ prompt_upsampling: P_VIDEO_DEFAULTS.promptUpsampling
3180
+ };
3181
+ }
3182
+ };
3183
+
3184
+ // src/providers/pruna/client/generation/builders/model-input-builder.ts
3185
+ var ModelInputBuilderRegistry = class {
3186
+ builders = /* @__PURE__ */ new Map();
3187
+ register(builder) {
3188
+ this.builders.set(builder.model, builder);
3189
+ return this;
3190
+ }
3191
+ resolve(model) {
3192
+ const builder = this.builders.get(model);
3193
+ if (!builder) {
3194
+ throw new Error(`No input builder registered for model: ${model}`);
3195
+ }
3196
+ return builder;
3197
+ }
3198
+ };
3199
+
3200
+ // src/providers/pruna/client/generation/builders/builder-factory.ts
3201
+ function createDefaultBuilderRegistry() {
3202
+ return new ModelInputBuilderRegistry().register(new TextToImageInputBuilder()).register(new ImageToImageInputBuilder()).register(new ImageToVideoInputBuilder());
3203
+ }
3204
+
3205
+ // src/providers/pruna/client/generation/services/generation.service.ts
3206
+ var builderRegistry = createDefaultBuilderRegistry();
3207
+ function validateGenerateInput(input) {
3208
+ assertValidPrompt(input.prompt, `${input.model}.prompt`);
3209
+ assertValidAspectRatio(input.aspect_ratio, `${input.model}.aspect_ratio`);
3210
+ if (isTextToImageInput(input)) {
3211
+ assertValidSeed(input.seed, `${input.model}.seed`);
3212
+ } else if (isImageToImageInput(input)) {
3213
+ assertSecureImageSource(input.image, `${input.model}.image`);
3214
+ assertValidSeed(input.seed, `${input.model}.seed`);
3215
+ } else if (isImageToVideoInput(input)) {
3216
+ assertSecureImageSource(input.image, `${input.model}.image`);
3217
+ assertValidDuration(input.duration, `${input.model}.duration`);
3218
+ assertValidResolution(input.resolution, `${input.model}.resolution`);
3219
+ }
3220
+ }
3221
+ async function generate(apiKey, input, options = {}) {
3222
+ assertValidApiKey(apiKey);
3223
+ validateGenerateInput(input);
3224
+ const { signal, onProgress, useCache = true } = options;
3225
+ if (useCache) {
3226
+ const cacheKey = deriveGenerationCacheKey(apiKey, input);
3227
+ return globalDeduplicator.execute(
3228
+ cacheKey,
3229
+ () => generateInternal(apiKey, input, { signal, onProgress })
3230
+ );
3231
+ }
3232
+ return generateInternal(apiKey, input, { signal, onProgress });
3233
+ }
3234
+ async function generateInternal(apiKey, input, options) {
3235
+ const { signal, onProgress } = options;
3236
+ const builder = builderRegistry.resolve(input.model);
3237
+ const modelInput = await builder.build(input, { apiKey, signal, onProgress });
3238
+ const response = await submitPrediction(input.model, modelInput, apiKey, signal, onProgress);
3239
+ const syncUri = extractUri(response);
3240
+ if (syncUri) {
3241
+ return { url: resolveUri(syncUri), model: input.model };
3242
+ }
3243
+ const pollUrl = response.get_url ?? response.status_url;
2584
3244
  if (!pollUrl) {
2585
- throw new Error("Pruna prediction response missing polling URL");
3245
+ throw new Error("Pruna API returned no result and no polling URL.");
3246
+ }
3247
+ const url = await pollForResult(
3248
+ pollUrl,
3249
+ apiKey,
3250
+ POLL_DEFAULTS.maxAttempts,
3251
+ POLL_DEFAULTS.intervalMs,
3252
+ signal,
3253
+ onProgress
3254
+ );
3255
+ return { url, model: input.model };
3256
+ }
3257
+ async function generateImageThenVideo(apiKey, input, options = {}) {
3258
+ assertValidApiKey(apiKey);
3259
+ assertValidPrompt(input.prompt, "text-to-video.prompt");
3260
+ assertValidAspectRatio(input.aspect_ratio, "text-to-video.aspect_ratio");
3261
+ assertValidDuration(input.duration, "text-to-video.duration");
3262
+ assertValidResolution(input.resolution, "text-to-video.resolution");
3263
+ const { signal, onProgress } = options;
3264
+ const aspectRatio = input.aspect_ratio ?? DEFAULT_ASPECT_RATIO;
3265
+ onProgress?.("predicting", 1);
3266
+ const imageResult = await generate(
3267
+ apiKey,
3268
+ { model: "p-image", prompt: input.prompt, aspect_ratio: aspectRatio },
3269
+ { signal }
3270
+ );
3271
+ onProgress?.("predicting", 2);
3272
+ return generate(
3273
+ apiKey,
3274
+ {
3275
+ model: "p-video",
3276
+ prompt: input.prompt,
3277
+ image: imageResult.url,
3278
+ duration: input.duration ?? P_VIDEO_DEFAULTS.duration,
3279
+ resolution: input.resolution ?? P_VIDEO_DEFAULTS.resolution,
3280
+ aspect_ratio: aspectRatio,
3281
+ draft: input.draft ?? P_VIDEO_DEFAULTS.draft
3282
+ },
3283
+ { signal, onProgress }
3284
+ );
3285
+ }
3286
+
3287
+ // src/providers/pruna/pruna-generate.ts
3288
+ async function* generateWithPruna(request, apiKey, signal, onProgress) {
3289
+ const stages = [];
3290
+ let notify = null;
3291
+ let done = false;
3292
+ const wake = () => {
3293
+ const fn = notify;
3294
+ if (fn) {
3295
+ notify = null;
3296
+ fn();
3297
+ }
3298
+ };
3299
+ const handleProgress = (stage) => {
3300
+ stages.push({ stage });
3301
+ onProgress?.(stage);
3302
+ wake();
3303
+ };
3304
+ const promise = (async () => {
3305
+ try {
3306
+ const model = request.model ?? (request.image ? "p-image-edit" : "p-image");
3307
+ if (model === "p-video" && !request.image && request.prompt) {
3308
+ const videoRes = await generateImageThenVideo(
3309
+ apiKey,
3310
+ {
3311
+ prompt: request.prompt,
3312
+ duration: request.duration ?? 5,
3313
+ aspect_ratio: request.aspectRatio ?? request.aspect_ratio ?? "16:9"
3314
+ },
3315
+ { signal, onProgress: handleProgress }
3316
+ );
3317
+ stages.push({
3318
+ stage: "polling",
3319
+ result: { url: videoRes.url, model: "p-video" }
3320
+ });
3321
+ return;
3322
+ }
3323
+ const input = {
3324
+ model,
3325
+ prompt: request.prompt ?? "",
3326
+ aspect_ratio: request.aspectRatio ?? request.aspect_ratio ?? "1:1",
3327
+ ...request.image ? { image: request.image } : {},
3328
+ ...request.duration ? { duration: request.duration } : {},
3329
+ ...request.resolution ? { resolution: request.resolution } : {},
3330
+ ...request.seed !== void 0 ? { seed: request.seed } : {}
3331
+ };
3332
+ const res = await generate(apiKey, input, {
3333
+ signal,
3334
+ onProgress: handleProgress
3335
+ });
3336
+ stages.push({
3337
+ stage: "polling",
3338
+ result: { url: res.url, model: res.model }
3339
+ });
3340
+ } catch (err) {
3341
+ stages.push({
3342
+ stage: "processing",
3343
+ error: err instanceof Error ? err : new Error(String(err))
3344
+ });
3345
+ } finally {
3346
+ done = true;
3347
+ wake();
3348
+ }
3349
+ })();
3350
+ while (!done || stages.length > 0) {
3351
+ if (stages.length === 0 && !done) {
3352
+ await new Promise((resolve) => {
3353
+ notify = resolve;
3354
+ });
3355
+ notify = null;
3356
+ }
3357
+ while (stages.length > 0) {
3358
+ const nextStage = stages.shift();
3359
+ if (!nextStage) continue;
3360
+ yield nextStage;
3361
+ if (nextStage.error) {
3362
+ throw nextStage.error;
3363
+ }
3364
+ }
2586
3365
  }
2587
- const resultUrl = await prunaCore.pollForResult(pollUrl, apiKey, 60, 2e3, signal, onProgress);
2588
- yield { stage: "polling", result: { url: resultUrl, model: modelId } };
3366
+ await promise;
2589
3367
  }
2590
3368
 
2591
3369
  // src/providers/pruna/pruna.provider.ts
@@ -3196,6 +3974,6 @@ function resetProvider() {
3196
3974
  container = null;
3197
3975
  }
3198
3976
 
3199
- export { ANTHROPIC_API_VERSION, ANTHROPIC_DEFAULT_MAX_TOKENS, ANTHROPIC_MODELS, ANTHROPIC_TIERS, API_ENDPOINTS, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, BaseProvider, DEFAULT_BASE_URL, DEFAULT_GENERATION_CONFIG, DEFAULT_MODELS, FalProvider, GEMINI_TIERS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GroqChatRequestBuilder, GroqConfigStore, GroqHttpClient, GroqHttpTransport, GroqProvider, ProviderError, ProviderFactory, PrunaProvider, TIMEOUTS, TextGenerationService, configureProvider, consumeAnthropicStream, consumeGroqStream, createAI, createAssistantMessage, createFalProvider, createGeminiProvider, createMessage, createPrunaProvider, createSystemMessage, createUserMessage, defaultEffortForModel, extractContentFromSsePayload, extractTextFromMessages, formatMessagesForDisplay, generateWithPruna, getProvider, isMediaProvider, isTextProvider, mapAnthropicStopReason, promptToMessages, requestStructuredJson, resetProvider, toGroqMessages };
3977
+ export { ANTHROPIC_API_VERSION, ANTHROPIC_DEFAULT_MAX_TOKENS, ANTHROPIC_MODELS, ANTHROPIC_TIERS, API_ENDPOINTS, AnthropicHttpTransport, AnthropicProvider, AnthropicRequestBuilder, AuthenticationError, BaseProvider as BaseAIProvider, BaseProvider, CancellationError, DEFAULT_BASE_URL, DEFAULT_GENERATION_CONFIG, DEFAULT_MODELS, FalProvider, GEMINI_TIERS, GROQ_MODELS, GROQ_TIERS, GeminiProvider, GenerationFailedError, GroqChatRequestBuilder, GroqConfigStore, GroqHttpClient, GroqHttpTransport, GroqProvider, ProviderError, ProviderFactory, PrunaProvider, TIMEOUTS, TextGenerationService, TimeoutError, ValidationError, configureProvider, consumeAnthropicStream, consumeGroqStream, createAI, createAssistantMessage, createFalProvider, createGeminiProvider, createGroqProvider, createMessage, createProviderFactory, createPrunaProvider, createSystemMessage, createUserMessage, defaultEffortForModel, extractContentFromSsePayload, extractTextFromMessages, formatMessagesForDisplay, generateImageThenVideo, generate as generatePruna, generateWithPruna, getProvider, isMediaProvider, isTextProvider, mapAnthropicStopReason, pollForResult, promptToMessages, requestStructuredJson, resetProvider, submitPrediction, toGroqMessages, uploadImage };
3200
3978
  //# sourceMappingURL=index.js.map
3201
3979
  //# sourceMappingURL=index.js.map