web-audio-recorder-ts 1.0.1 → 1.0.3

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.
package/dist/index.cjs.js CHANGED
@@ -438,12 +438,20 @@ function getEncoderBaseUrl() {
438
438
  const parts = __dirname.split('node_modules/');
439
439
  if (parts.length > 1) {
440
440
  const packageName = parts[1].split('/')[0];
441
+ // Retornar caminho absoluto se possível
442
+ if (typeof window !== 'undefined') {
443
+ return `${window.location.origin}/node_modules/${packageName}/lib`;
444
+ }
441
445
  return `/node_modules/${packageName}/lib`;
442
446
  }
443
447
  }
444
448
  // If in dist, go to lib
445
449
  if (__dirname.includes('dist')) {
446
- return __dirname.replace('dist', 'lib');
450
+ const libPath = __dirname.replace('dist', 'lib');
451
+ if (typeof window !== 'undefined') {
452
+ return `${window.location.origin}${libPath}`;
453
+ }
454
+ return libPath;
447
455
  }
448
456
  }
449
457
  catch (e) {
@@ -472,6 +480,7 @@ function getEncoderBaseUrl() {
472
480
  if (url.pathname.includes('node_modules')) {
473
481
  const packagePath = url.pathname.split('node_modules/')[1];
474
482
  const packageName = packagePath.split('/')[0];
483
+ // Retornar caminho absoluto para node_modules
475
484
  return `${url.origin}/node_modules/${packageName}/lib`;
476
485
  }
477
486
  // If from dist, go to lib
@@ -485,11 +494,10 @@ function getEncoderBaseUrl() {
485
494
  }
486
495
  }
487
496
  }
488
- // Default fallback: try common paths
489
- // In browser, try root first (for Vite public/), then node_modules, then lib
497
+ // Default fallback: try node_modules first, then root
490
498
  if (typeof window !== 'undefined') {
491
- // For development with Vite, public/ is served at root
492
- return '/';
499
+ // Priorizar node_modules
500
+ return '/node_modules/web-audio-recorder-ts/lib';
493
501
  }
494
502
  return '/lib';
495
503
  }
@@ -541,22 +549,24 @@ function configureEncoderPaths(baseUrl) {
541
549
  * Useful when auto-detection fails
542
550
  */
543
551
  async function findEncoderPath(filename) {
552
+ // Priorizar caminhos do node_modules primeiro
544
553
  const possiblePaths = [
545
- // For development/demo: try public folder first (Vite serves public/ at root)
546
- `/${filename}`,
547
- // Direct lib paths (for development or custom setups)
548
- `/lib/${filename}`,
549
- `./lib/${filename}`,
550
- `../lib/${filename}`,
551
- // Auto-detected path
552
- getEncoderScriptUrl(filename),
553
- // Common npm package paths (from node_modules) - only works if server is configured
554
+ // Primeiro: tentar node_modules (prioridade máxima)
554
555
  `/node_modules/web-audio-recorder-ts/lib/${filename}`,
555
556
  `./node_modules/web-audio-recorder-ts/lib/${filename}`,
556
557
  `../node_modules/web-audio-recorder-ts/lib/${filename}`,
557
- // From dist (if bundled)
558
+ `../../node_modules/web-audio-recorder-ts/lib/${filename}`,
559
+ // From dist (se os arquivos foram copiados para dist/lib)
558
560
  `/node_modules/web-audio-recorder-ts/dist/lib/${filename}`,
559
561
  `./node_modules/web-audio-recorder-ts/dist/lib/${filename}`,
562
+ // Auto-detected path (pode apontar para node_modules)
563
+ getEncoderScriptUrl(filename),
564
+ // Para desenvolvimento/demo: try public folder (Vite serves public/ at root)
565
+ `/${filename}`,
566
+ // Direct lib paths (for development or custom setups)
567
+ `/lib/${filename}`,
568
+ `./lib/${filename}`,
569
+ `../lib/${filename}`,
560
570
  // CDN or absolute paths (if configured)
561
571
  filename.startsWith('http') ? filename : null
562
572
  ].filter((path) => path !== null);
@@ -566,9 +576,22 @@ async function findEncoderPath(filename) {
566
576
  const testUrl = path.startsWith('http')
567
577
  ? path
568
578
  : new URL(path, typeof window !== 'undefined' ? window.location.href : 'file://').href;
569
- const response = await fetch(testUrl, { method: 'HEAD' });
579
+ // Usar GET para verificar se é JavaScript válido (não HTML)
580
+ const response = await fetch(testUrl, { method: 'GET', cache: 'no-cache' });
570
581
  if (response.ok) {
571
- return path;
582
+ // Verificar se o conteúdo é JavaScript (não HTML)
583
+ const text = await response.text();
584
+ const trimmedText = text.trim();
585
+ // Se começar com '<', é HTML (404, etc) - pular este caminho
586
+ if (trimmedText.startsWith('<')) {
587
+ console.warn(`Path ${path} returned HTML instead of JavaScript, skipping...`);
588
+ continue;
589
+ }
590
+ // Se parece JavaScript, retornar este caminho
591
+ if (trimmedText.includes('function') || trimmedText.includes('var') || trimmedText.includes('const') || trimmedText.includes('let') || trimmedText.length > 100) {
592
+ console.log(`✅ Found encoder file at: ${path}`);
593
+ return path;
594
+ }
572
595
  }
573
596
  }
574
597
  catch (e) {
@@ -702,38 +725,71 @@ function loadOggVorbisEncoderInternal(scriptUrl) {
702
725
  });
703
726
  return;
704
727
  }
705
- // Primeiro, verificar se o arquivo existe fazendo uma requisição HEAD
706
- fetch(scriptUrl, { method: 'HEAD', cache: 'no-cache' })
728
+ // Verificar se o arquivo existe e é JavaScript válido
729
+ fetch(scriptUrl, { method: 'GET', cache: 'no-cache' })
707
730
  .then(response => {
708
731
  if (!response.ok) {
709
- throw new Error(`File not found: ${scriptUrl} (${response.status})`);
732
+ throw new Error(`File not found: ${scriptUrl} (${response.status} ${response.statusText}). Make sure the file exists and is accessible.`);
710
733
  }
711
- // Criar e carregar novo script
712
- const script = document.createElement('script');
713
- script.src = scriptUrl;
714
- script.async = false; // Carregar de forma síncrona para garantir ordem
715
- script.type = 'text/javascript';
716
- script.onload = () => {
717
- // Aguardar um pouco para garantir que o objeto global foi criado
718
- setTimeout(() => {
719
- if (typeof window.OggVorbisEncoder !== 'undefined') {
720
- resolve();
721
- }
722
- else {
723
- reject(new Error('OggVorbisEncoder object not found after script load. The script may not have exported the global correctly.'));
724
- }
725
- }, 200);
726
- };
727
- script.onerror = (event) => {
728
- const error = new Error(`Failed to load OggVorbisEncoder script from ${scriptUrl}. Check browser console for CORS or network errors.`);
729
- console.error('Script load error:', event);
730
- console.error('Script URL:', scriptUrl);
731
- reject(error);
732
- };
733
- document.head.appendChild(script);
734
+ // Verificar Content-Type
735
+ const contentType = response.headers.get('content-type') || '';
736
+ if (!contentType.includes('javascript') && !contentType.includes('application/javascript') && !contentType.includes('text/javascript')) {
737
+ console.warn(`Warning: Content-Type is "${contentType}", expected JavaScript. Proceeding with validation...`);
738
+ }
739
+ // Verificar se o conteúdo é JavaScript (não HTML)
740
+ return response.text().then(text => {
741
+ const trimmedText = text.trim();
742
+ // Se começar com '<', provavelmente é HTML (erro 404, etc)
743
+ if (trimmedText.startsWith('<')) {
744
+ const errorMsg = `Invalid response from ${scriptUrl}. Expected JavaScript but received HTML (likely a 404 error page).\n\n` +
745
+ `The file was not found at this path. Please:\n` +
746
+ `1. Verify the file exists at: ${scriptUrl}\n` +
747
+ `2. Check if you need to copy files to your public/ folder\n` +
748
+ `3. Ensure your server is configured to serve the file\n` +
749
+ `4. Try accessing the URL directly in your browser`;
750
+ console.error(errorMsg);
751
+ reject(new Error(errorMsg));
752
+ return; // Não continuar se for HTML
753
+ }
754
+ // Verificar se parece com JavaScript (contém pelo menos algumas palavras-chave comuns)
755
+ if (!trimmedText.includes('function') && !trimmedText.includes('var') && !trimmedText.includes('const') && !trimmedText.includes('let')) {
756
+ console.warn(`Warning: Response from ${scriptUrl} does not appear to be valid JavaScript.`);
757
+ }
758
+ // Criar e carregar novo script
759
+ const script = document.createElement('script');
760
+ script.src = scriptUrl;
761
+ script.async = false; // Carregar de forma síncrona para garantir ordem
762
+ script.type = 'text/javascript';
763
+ script.onload = () => {
764
+ // Aguardar um pouco para garantir que o objeto global foi criado
765
+ setTimeout(() => {
766
+ if (typeof window.OggVorbisEncoder !== 'undefined') {
767
+ resolve();
768
+ }
769
+ else {
770
+ reject(new Error(`OggVorbisEncoder object not found after script load from ${scriptUrl}. The script may not have exported the global correctly, or the file may be corrupted.`));
771
+ }
772
+ }, 200);
773
+ };
774
+ script.onerror = (event) => {
775
+ const error = new Error(`Failed to load OggVorbisEncoder script from ${scriptUrl}. Check browser console for CORS or network errors. Make sure the file exists and is accessible.`);
776
+ console.error('Script load error:', event);
777
+ console.error('Script URL:', scriptUrl);
778
+ console.error('Try accessing the URL directly in your browser to verify it exists.');
779
+ reject(error);
780
+ };
781
+ document.head.appendChild(script);
782
+ });
734
783
  })
735
784
  .catch(error => {
736
- reject(new Error(`Cannot access OggVorbisEncoder script at ${scriptUrl}: ${error.message}`));
785
+ const errorMsg = `Cannot access OggVorbisEncoder script at ${scriptUrl}: ${error.message}\n\n` +
786
+ `Troubleshooting:\n` +
787
+ `1. Open ${scriptUrl} in your browser to verify the file exists\n` +
788
+ `2. Check browser console for CORS errors\n` +
789
+ `3. Ensure your server is configured to serve files from node_modules or public folder\n` +
790
+ `4. See TROUBLESHOOTING_ENCODER.md for more help`;
791
+ console.error(errorMsg);
792
+ reject(new Error(errorMsg));
737
793
  });
738
794
  });
739
795
  }
@@ -861,38 +917,71 @@ function loadMp3LameEncoderInternal(scriptUrl) {
861
917
  });
862
918
  return;
863
919
  }
864
- // Primeiro, verificar se o arquivo existe fazendo uma requisição HEAD
865
- fetch(scriptUrl, { method: 'HEAD', cache: 'no-cache' })
920
+ // Verificar se o arquivo existe e é JavaScript válido
921
+ fetch(scriptUrl, { method: 'GET', cache: 'no-cache' })
866
922
  .then(response => {
867
923
  if (!response.ok) {
868
- throw new Error(`File not found: ${scriptUrl} (${response.status})`);
924
+ throw new Error(`File not found: ${scriptUrl} (${response.status} ${response.statusText}). Make sure the file exists and is accessible.`);
869
925
  }
870
- // Criar e carregar novo script
871
- const script = document.createElement('script');
872
- script.src = scriptUrl;
873
- script.async = false; // Carregar de forma síncrona para garantir ordem
874
- script.type = 'text/javascript';
875
- script.onload = () => {
876
- // Aguardar um pouco para garantir que o objeto global foi criado
877
- setTimeout(() => {
878
- if (typeof window.Mp3LameEncoder !== 'undefined') {
879
- resolve();
880
- }
881
- else {
882
- reject(new Error('Mp3LameEncoder object not found after script load. The script may not have exported the global correctly.'));
883
- }
884
- }, 200);
885
- };
886
- script.onerror = (event) => {
887
- const error = new Error(`Failed to load Mp3LameEncoder script from ${scriptUrl}. Check browser console for CORS or network errors.`);
888
- console.error('Script load error:', event);
889
- console.error('Script URL:', scriptUrl);
890
- reject(error);
891
- };
892
- document.head.appendChild(script);
926
+ // Verificar Content-Type
927
+ const contentType = response.headers.get('content-type') || '';
928
+ if (!contentType.includes('javascript') && !contentType.includes('application/javascript') && !contentType.includes('text/javascript')) {
929
+ console.warn(`Warning: Content-Type is "${contentType}", expected JavaScript. Proceeding with validation...`);
930
+ }
931
+ // Verificar se o conteúdo é JavaScript (não HTML)
932
+ return response.text().then(text => {
933
+ const trimmedText = text.trim();
934
+ // Se começar com '<', provavelmente é HTML (erro 404, etc)
935
+ if (trimmedText.startsWith('<')) {
936
+ const errorMsg = `Invalid response from ${scriptUrl}. Expected JavaScript but received HTML (likely a 404 error page).\n\n` +
937
+ `The file was not found at this path. Please:\n` +
938
+ `1. Verify the file exists at: ${scriptUrl}\n` +
939
+ `2. Check if you need to copy files to your public/ folder\n` +
940
+ `3. Ensure your server is configured to serve the file\n` +
941
+ `4. Try accessing the URL directly in your browser`;
942
+ console.error(errorMsg);
943
+ reject(new Error(errorMsg));
944
+ return; // Não continuar se for HTML
945
+ }
946
+ // Verificar se parece com JavaScript (contém pelo menos algumas palavras-chave comuns)
947
+ if (!trimmedText.includes('function') && !trimmedText.includes('var') && !trimmedText.includes('const') && !trimmedText.includes('let')) {
948
+ console.warn(`Warning: Response from ${scriptUrl} does not appear to be valid JavaScript.`);
949
+ }
950
+ // Criar e carregar novo script
951
+ const script = document.createElement('script');
952
+ script.src = scriptUrl;
953
+ script.async = false; // Carregar de forma síncrona para garantir ordem
954
+ script.type = 'text/javascript';
955
+ script.onload = () => {
956
+ // Aguardar um pouco para garantir que o objeto global foi criado
957
+ setTimeout(() => {
958
+ if (typeof window.Mp3LameEncoder !== 'undefined') {
959
+ resolve();
960
+ }
961
+ else {
962
+ reject(new Error(`Mp3LameEncoder object not found after script load from ${scriptUrl}. The script may not have exported the global correctly, or the file may be corrupted.`));
963
+ }
964
+ }, 200);
965
+ };
966
+ script.onerror = (event) => {
967
+ const error = new Error(`Failed to load Mp3LameEncoder script from ${scriptUrl}. Check browser console for CORS or network errors. Make sure the file exists and is accessible.`);
968
+ console.error('Script load error:', event);
969
+ console.error('Script URL:', scriptUrl);
970
+ console.error('Try accessing the URL directly in your browser to verify it exists.');
971
+ reject(error);
972
+ };
973
+ document.head.appendChild(script);
974
+ });
893
975
  })
894
976
  .catch(error => {
895
- reject(new Error(`Cannot access Mp3LameEncoder script at ${scriptUrl}: ${error.message}`));
977
+ const errorMsg = `Cannot access Mp3LameEncoder script at ${scriptUrl}: ${error.message}\n\n` +
978
+ `Troubleshooting:\n` +
979
+ `1. Open ${scriptUrl} in your browser to verify the file exists\n` +
980
+ `2. Check browser console for CORS errors\n` +
981
+ `3. Ensure your server is configured to serve files from node_modules or public folder\n` +
982
+ `4. See TROUBLESHOOTING_ENCODER.md for more help`;
983
+ console.error(errorMsg);
984
+ reject(new Error(errorMsg));
896
985
  });
897
986
  });
898
987
  }
package/dist/index.esm.js CHANGED
@@ -435,12 +435,20 @@ function getEncoderBaseUrl() {
435
435
  const parts = __dirname.split('node_modules/');
436
436
  if (parts.length > 1) {
437
437
  const packageName = parts[1].split('/')[0];
438
+ // Retornar caminho absoluto se possível
439
+ if (typeof window !== 'undefined') {
440
+ return `${window.location.origin}/node_modules/${packageName}/lib`;
441
+ }
438
442
  return `/node_modules/${packageName}/lib`;
439
443
  }
440
444
  }
441
445
  // If in dist, go to lib
442
446
  if (__dirname.includes('dist')) {
443
- return __dirname.replace('dist', 'lib');
447
+ const libPath = __dirname.replace('dist', 'lib');
448
+ if (typeof window !== 'undefined') {
449
+ return `${window.location.origin}${libPath}`;
450
+ }
451
+ return libPath;
444
452
  }
445
453
  }
446
454
  catch (e) {
@@ -469,6 +477,7 @@ function getEncoderBaseUrl() {
469
477
  if (url.pathname.includes('node_modules')) {
470
478
  const packagePath = url.pathname.split('node_modules/')[1];
471
479
  const packageName = packagePath.split('/')[0];
480
+ // Retornar caminho absoluto para node_modules
472
481
  return `${url.origin}/node_modules/${packageName}/lib`;
473
482
  }
474
483
  // If from dist, go to lib
@@ -482,11 +491,10 @@ function getEncoderBaseUrl() {
482
491
  }
483
492
  }
484
493
  }
485
- // Default fallback: try common paths
486
- // In browser, try root first (for Vite public/), then node_modules, then lib
494
+ // Default fallback: try node_modules first, then root
487
495
  if (typeof window !== 'undefined') {
488
- // For development with Vite, public/ is served at root
489
- return '/';
496
+ // Priorizar node_modules
497
+ return '/node_modules/web-audio-recorder-ts/lib';
490
498
  }
491
499
  return '/lib';
492
500
  }
@@ -538,22 +546,24 @@ function configureEncoderPaths(baseUrl) {
538
546
  * Useful when auto-detection fails
539
547
  */
540
548
  async function findEncoderPath(filename) {
549
+ // Priorizar caminhos do node_modules primeiro
541
550
  const possiblePaths = [
542
- // For development/demo: try public folder first (Vite serves public/ at root)
543
- `/${filename}`,
544
- // Direct lib paths (for development or custom setups)
545
- `/lib/${filename}`,
546
- `./lib/${filename}`,
547
- `../lib/${filename}`,
548
- // Auto-detected path
549
- getEncoderScriptUrl(filename),
550
- // Common npm package paths (from node_modules) - only works if server is configured
551
+ // Primeiro: tentar node_modules (prioridade máxima)
551
552
  `/node_modules/web-audio-recorder-ts/lib/${filename}`,
552
553
  `./node_modules/web-audio-recorder-ts/lib/${filename}`,
553
554
  `../node_modules/web-audio-recorder-ts/lib/${filename}`,
554
- // From dist (if bundled)
555
+ `../../node_modules/web-audio-recorder-ts/lib/${filename}`,
556
+ // From dist (se os arquivos foram copiados para dist/lib)
555
557
  `/node_modules/web-audio-recorder-ts/dist/lib/${filename}`,
556
558
  `./node_modules/web-audio-recorder-ts/dist/lib/${filename}`,
559
+ // Auto-detected path (pode apontar para node_modules)
560
+ getEncoderScriptUrl(filename),
561
+ // Para desenvolvimento/demo: try public folder (Vite serves public/ at root)
562
+ `/${filename}`,
563
+ // Direct lib paths (for development or custom setups)
564
+ `/lib/${filename}`,
565
+ `./lib/${filename}`,
566
+ `../lib/${filename}`,
557
567
  // CDN or absolute paths (if configured)
558
568
  filename.startsWith('http') ? filename : null
559
569
  ].filter((path) => path !== null);
@@ -563,9 +573,22 @@ async function findEncoderPath(filename) {
563
573
  const testUrl = path.startsWith('http')
564
574
  ? path
565
575
  : new URL(path, typeof window !== 'undefined' ? window.location.href : 'file://').href;
566
- const response = await fetch(testUrl, { method: 'HEAD' });
576
+ // Usar GET para verificar se é JavaScript válido (não HTML)
577
+ const response = await fetch(testUrl, { method: 'GET', cache: 'no-cache' });
567
578
  if (response.ok) {
568
- return path;
579
+ // Verificar se o conteúdo é JavaScript (não HTML)
580
+ const text = await response.text();
581
+ const trimmedText = text.trim();
582
+ // Se começar com '<', é HTML (404, etc) - pular este caminho
583
+ if (trimmedText.startsWith('<')) {
584
+ console.warn(`Path ${path} returned HTML instead of JavaScript, skipping...`);
585
+ continue;
586
+ }
587
+ // Se parece JavaScript, retornar este caminho
588
+ if (trimmedText.includes('function') || trimmedText.includes('var') || trimmedText.includes('const') || trimmedText.includes('let') || trimmedText.length > 100) {
589
+ console.log(`✅ Found encoder file at: ${path}`);
590
+ return path;
591
+ }
569
592
  }
570
593
  }
571
594
  catch (e) {
@@ -699,38 +722,71 @@ function loadOggVorbisEncoderInternal(scriptUrl) {
699
722
  });
700
723
  return;
701
724
  }
702
- // Primeiro, verificar se o arquivo existe fazendo uma requisição HEAD
703
- fetch(scriptUrl, { method: 'HEAD', cache: 'no-cache' })
725
+ // Verificar se o arquivo existe e é JavaScript válido
726
+ fetch(scriptUrl, { method: 'GET', cache: 'no-cache' })
704
727
  .then(response => {
705
728
  if (!response.ok) {
706
- throw new Error(`File not found: ${scriptUrl} (${response.status})`);
729
+ throw new Error(`File not found: ${scriptUrl} (${response.status} ${response.statusText}). Make sure the file exists and is accessible.`);
707
730
  }
708
- // Criar e carregar novo script
709
- const script = document.createElement('script');
710
- script.src = scriptUrl;
711
- script.async = false; // Carregar de forma síncrona para garantir ordem
712
- script.type = 'text/javascript';
713
- script.onload = () => {
714
- // Aguardar um pouco para garantir que o objeto global foi criado
715
- setTimeout(() => {
716
- if (typeof window.OggVorbisEncoder !== 'undefined') {
717
- resolve();
718
- }
719
- else {
720
- reject(new Error('OggVorbisEncoder object not found after script load. The script may not have exported the global correctly.'));
721
- }
722
- }, 200);
723
- };
724
- script.onerror = (event) => {
725
- const error = new Error(`Failed to load OggVorbisEncoder script from ${scriptUrl}. Check browser console for CORS or network errors.`);
726
- console.error('Script load error:', event);
727
- console.error('Script URL:', scriptUrl);
728
- reject(error);
729
- };
730
- document.head.appendChild(script);
731
+ // Verificar Content-Type
732
+ const contentType = response.headers.get('content-type') || '';
733
+ if (!contentType.includes('javascript') && !contentType.includes('application/javascript') && !contentType.includes('text/javascript')) {
734
+ console.warn(`Warning: Content-Type is "${contentType}", expected JavaScript. Proceeding with validation...`);
735
+ }
736
+ // Verificar se o conteúdo é JavaScript (não HTML)
737
+ return response.text().then(text => {
738
+ const trimmedText = text.trim();
739
+ // Se começar com '<', provavelmente é HTML (erro 404, etc)
740
+ if (trimmedText.startsWith('<')) {
741
+ const errorMsg = `Invalid response from ${scriptUrl}. Expected JavaScript but received HTML (likely a 404 error page).\n\n` +
742
+ `The file was not found at this path. Please:\n` +
743
+ `1. Verify the file exists at: ${scriptUrl}\n` +
744
+ `2. Check if you need to copy files to your public/ folder\n` +
745
+ `3. Ensure your server is configured to serve the file\n` +
746
+ `4. Try accessing the URL directly in your browser`;
747
+ console.error(errorMsg);
748
+ reject(new Error(errorMsg));
749
+ return; // Não continuar se for HTML
750
+ }
751
+ // Verificar se parece com JavaScript (contém pelo menos algumas palavras-chave comuns)
752
+ if (!trimmedText.includes('function') && !trimmedText.includes('var') && !trimmedText.includes('const') && !trimmedText.includes('let')) {
753
+ console.warn(`Warning: Response from ${scriptUrl} does not appear to be valid JavaScript.`);
754
+ }
755
+ // Criar e carregar novo script
756
+ const script = document.createElement('script');
757
+ script.src = scriptUrl;
758
+ script.async = false; // Carregar de forma síncrona para garantir ordem
759
+ script.type = 'text/javascript';
760
+ script.onload = () => {
761
+ // Aguardar um pouco para garantir que o objeto global foi criado
762
+ setTimeout(() => {
763
+ if (typeof window.OggVorbisEncoder !== 'undefined') {
764
+ resolve();
765
+ }
766
+ else {
767
+ reject(new Error(`OggVorbisEncoder object not found after script load from ${scriptUrl}. The script may not have exported the global correctly, or the file may be corrupted.`));
768
+ }
769
+ }, 200);
770
+ };
771
+ script.onerror = (event) => {
772
+ const error = new Error(`Failed to load OggVorbisEncoder script from ${scriptUrl}. Check browser console for CORS or network errors. Make sure the file exists and is accessible.`);
773
+ console.error('Script load error:', event);
774
+ console.error('Script URL:', scriptUrl);
775
+ console.error('Try accessing the URL directly in your browser to verify it exists.');
776
+ reject(error);
777
+ };
778
+ document.head.appendChild(script);
779
+ });
731
780
  })
732
781
  .catch(error => {
733
- reject(new Error(`Cannot access OggVorbisEncoder script at ${scriptUrl}: ${error.message}`));
782
+ const errorMsg = `Cannot access OggVorbisEncoder script at ${scriptUrl}: ${error.message}\n\n` +
783
+ `Troubleshooting:\n` +
784
+ `1. Open ${scriptUrl} in your browser to verify the file exists\n` +
785
+ `2. Check browser console for CORS errors\n` +
786
+ `3. Ensure your server is configured to serve files from node_modules or public folder\n` +
787
+ `4. See TROUBLESHOOTING_ENCODER.md for more help`;
788
+ console.error(errorMsg);
789
+ reject(new Error(errorMsg));
734
790
  });
735
791
  });
736
792
  }
@@ -858,38 +914,71 @@ function loadMp3LameEncoderInternal(scriptUrl) {
858
914
  });
859
915
  return;
860
916
  }
861
- // Primeiro, verificar se o arquivo existe fazendo uma requisição HEAD
862
- fetch(scriptUrl, { method: 'HEAD', cache: 'no-cache' })
917
+ // Verificar se o arquivo existe e é JavaScript válido
918
+ fetch(scriptUrl, { method: 'GET', cache: 'no-cache' })
863
919
  .then(response => {
864
920
  if (!response.ok) {
865
- throw new Error(`File not found: ${scriptUrl} (${response.status})`);
921
+ throw new Error(`File not found: ${scriptUrl} (${response.status} ${response.statusText}). Make sure the file exists and is accessible.`);
866
922
  }
867
- // Criar e carregar novo script
868
- const script = document.createElement('script');
869
- script.src = scriptUrl;
870
- script.async = false; // Carregar de forma síncrona para garantir ordem
871
- script.type = 'text/javascript';
872
- script.onload = () => {
873
- // Aguardar um pouco para garantir que o objeto global foi criado
874
- setTimeout(() => {
875
- if (typeof window.Mp3LameEncoder !== 'undefined') {
876
- resolve();
877
- }
878
- else {
879
- reject(new Error('Mp3LameEncoder object not found after script load. The script may not have exported the global correctly.'));
880
- }
881
- }, 200);
882
- };
883
- script.onerror = (event) => {
884
- const error = new Error(`Failed to load Mp3LameEncoder script from ${scriptUrl}. Check browser console for CORS or network errors.`);
885
- console.error('Script load error:', event);
886
- console.error('Script URL:', scriptUrl);
887
- reject(error);
888
- };
889
- document.head.appendChild(script);
923
+ // Verificar Content-Type
924
+ const contentType = response.headers.get('content-type') || '';
925
+ if (!contentType.includes('javascript') && !contentType.includes('application/javascript') && !contentType.includes('text/javascript')) {
926
+ console.warn(`Warning: Content-Type is "${contentType}", expected JavaScript. Proceeding with validation...`);
927
+ }
928
+ // Verificar se o conteúdo é JavaScript (não HTML)
929
+ return response.text().then(text => {
930
+ const trimmedText = text.trim();
931
+ // Se começar com '<', provavelmente é HTML (erro 404, etc)
932
+ if (trimmedText.startsWith('<')) {
933
+ const errorMsg = `Invalid response from ${scriptUrl}. Expected JavaScript but received HTML (likely a 404 error page).\n\n` +
934
+ `The file was not found at this path. Please:\n` +
935
+ `1. Verify the file exists at: ${scriptUrl}\n` +
936
+ `2. Check if you need to copy files to your public/ folder\n` +
937
+ `3. Ensure your server is configured to serve the file\n` +
938
+ `4. Try accessing the URL directly in your browser`;
939
+ console.error(errorMsg);
940
+ reject(new Error(errorMsg));
941
+ return; // Não continuar se for HTML
942
+ }
943
+ // Verificar se parece com JavaScript (contém pelo menos algumas palavras-chave comuns)
944
+ if (!trimmedText.includes('function') && !trimmedText.includes('var') && !trimmedText.includes('const') && !trimmedText.includes('let')) {
945
+ console.warn(`Warning: Response from ${scriptUrl} does not appear to be valid JavaScript.`);
946
+ }
947
+ // Criar e carregar novo script
948
+ const script = document.createElement('script');
949
+ script.src = scriptUrl;
950
+ script.async = false; // Carregar de forma síncrona para garantir ordem
951
+ script.type = 'text/javascript';
952
+ script.onload = () => {
953
+ // Aguardar um pouco para garantir que o objeto global foi criado
954
+ setTimeout(() => {
955
+ if (typeof window.Mp3LameEncoder !== 'undefined') {
956
+ resolve();
957
+ }
958
+ else {
959
+ reject(new Error(`Mp3LameEncoder object not found after script load from ${scriptUrl}. The script may not have exported the global correctly, or the file may be corrupted.`));
960
+ }
961
+ }, 200);
962
+ };
963
+ script.onerror = (event) => {
964
+ const error = new Error(`Failed to load Mp3LameEncoder script from ${scriptUrl}. Check browser console for CORS or network errors. Make sure the file exists and is accessible.`);
965
+ console.error('Script load error:', event);
966
+ console.error('Script URL:', scriptUrl);
967
+ console.error('Try accessing the URL directly in your browser to verify it exists.');
968
+ reject(error);
969
+ };
970
+ document.head.appendChild(script);
971
+ });
890
972
  })
891
973
  .catch(error => {
892
- reject(new Error(`Cannot access Mp3LameEncoder script at ${scriptUrl}: ${error.message}`));
974
+ const errorMsg = `Cannot access Mp3LameEncoder script at ${scriptUrl}: ${error.message}\n\n` +
975
+ `Troubleshooting:\n` +
976
+ `1. Open ${scriptUrl} in your browser to verify the file exists\n` +
977
+ `2. Check browser console for CORS errors\n` +
978
+ `3. Ensure your server is configured to serve files from node_modules or public folder\n` +
979
+ `4. See TROUBLESHOOTING_ENCODER.md for more help`;
980
+ console.error(errorMsg);
981
+ reject(new Error(errorMsg));
893
982
  });
894
983
  });
895
984
  }
package/dist/index.umd.js CHANGED
@@ -442,12 +442,20 @@
442
442
  const parts = __dirname.split('node_modules/');
443
443
  if (parts.length > 1) {
444
444
  const packageName = parts[1].split('/')[0];
445
+ // Retornar caminho absoluto se possível
446
+ if (typeof window !== 'undefined') {
447
+ return `${window.location.origin}/node_modules/${packageName}/lib`;
448
+ }
445
449
  return `/node_modules/${packageName}/lib`;
446
450
  }
447
451
  }
448
452
  // If in dist, go to lib
449
453
  if (__dirname.includes('dist')) {
450
- return __dirname.replace('dist', 'lib');
454
+ const libPath = __dirname.replace('dist', 'lib');
455
+ if (typeof window !== 'undefined') {
456
+ return `${window.location.origin}${libPath}`;
457
+ }
458
+ return libPath;
451
459
  }
452
460
  }
453
461
  catch (e) {
@@ -476,6 +484,7 @@
476
484
  if (url.pathname.includes('node_modules')) {
477
485
  const packagePath = url.pathname.split('node_modules/')[1];
478
486
  const packageName = packagePath.split('/')[0];
487
+ // Retornar caminho absoluto para node_modules
479
488
  return `${url.origin}/node_modules/${packageName}/lib`;
480
489
  }
481
490
  // If from dist, go to lib
@@ -489,11 +498,10 @@
489
498
  }
490
499
  }
491
500
  }
492
- // Default fallback: try common paths
493
- // In browser, try root first (for Vite public/), then node_modules, then lib
501
+ // Default fallback: try node_modules first, then root
494
502
  if (typeof window !== 'undefined') {
495
- // For development with Vite, public/ is served at root
496
- return '/';
503
+ // Priorizar node_modules
504
+ return '/node_modules/web-audio-recorder-ts/lib';
497
505
  }
498
506
  return '/lib';
499
507
  }
@@ -545,22 +553,24 @@
545
553
  * Useful when auto-detection fails
546
554
  */
547
555
  async function findEncoderPath(filename) {
556
+ // Priorizar caminhos do node_modules primeiro
548
557
  const possiblePaths = [
549
- // For development/demo: try public folder first (Vite serves public/ at root)
550
- `/${filename}`,
551
- // Direct lib paths (for development or custom setups)
552
- `/lib/${filename}`,
553
- `./lib/${filename}`,
554
- `../lib/${filename}`,
555
- // Auto-detected path
556
- getEncoderScriptUrl(filename),
557
- // Common npm package paths (from node_modules) - only works if server is configured
558
+ // Primeiro: tentar node_modules (prioridade máxima)
558
559
  `/node_modules/web-audio-recorder-ts/lib/${filename}`,
559
560
  `./node_modules/web-audio-recorder-ts/lib/${filename}`,
560
561
  `../node_modules/web-audio-recorder-ts/lib/${filename}`,
561
- // From dist (if bundled)
562
+ `../../node_modules/web-audio-recorder-ts/lib/${filename}`,
563
+ // From dist (se os arquivos foram copiados para dist/lib)
562
564
  `/node_modules/web-audio-recorder-ts/dist/lib/${filename}`,
563
565
  `./node_modules/web-audio-recorder-ts/dist/lib/${filename}`,
566
+ // Auto-detected path (pode apontar para node_modules)
567
+ getEncoderScriptUrl(filename),
568
+ // Para desenvolvimento/demo: try public folder (Vite serves public/ at root)
569
+ `/${filename}`,
570
+ // Direct lib paths (for development or custom setups)
571
+ `/lib/${filename}`,
572
+ `./lib/${filename}`,
573
+ `../lib/${filename}`,
564
574
  // CDN or absolute paths (if configured)
565
575
  filename.startsWith('http') ? filename : null
566
576
  ].filter((path) => path !== null);
@@ -570,9 +580,22 @@
570
580
  const testUrl = path.startsWith('http')
571
581
  ? path
572
582
  : new URL(path, typeof window !== 'undefined' ? window.location.href : 'file://').href;
573
- const response = await fetch(testUrl, { method: 'HEAD' });
583
+ // Usar GET para verificar se é JavaScript válido (não HTML)
584
+ const response = await fetch(testUrl, { method: 'GET', cache: 'no-cache' });
574
585
  if (response.ok) {
575
- return path;
586
+ // Verificar se o conteúdo é JavaScript (não HTML)
587
+ const text = await response.text();
588
+ const trimmedText = text.trim();
589
+ // Se começar com '<', é HTML (404, etc) - pular este caminho
590
+ if (trimmedText.startsWith('<')) {
591
+ console.warn(`Path ${path} returned HTML instead of JavaScript, skipping...`);
592
+ continue;
593
+ }
594
+ // Se parece JavaScript, retornar este caminho
595
+ if (trimmedText.includes('function') || trimmedText.includes('var') || trimmedText.includes('const') || trimmedText.includes('let') || trimmedText.length > 100) {
596
+ console.log(`✅ Found encoder file at: ${path}`);
597
+ return path;
598
+ }
576
599
  }
577
600
  }
578
601
  catch (e) {
@@ -706,38 +729,71 @@
706
729
  });
707
730
  return;
708
731
  }
709
- // Primeiro, verificar se o arquivo existe fazendo uma requisição HEAD
710
- fetch(scriptUrl, { method: 'HEAD', cache: 'no-cache' })
732
+ // Verificar se o arquivo existe e é JavaScript válido
733
+ fetch(scriptUrl, { method: 'GET', cache: 'no-cache' })
711
734
  .then(response => {
712
735
  if (!response.ok) {
713
- throw new Error(`File not found: ${scriptUrl} (${response.status})`);
736
+ throw new Error(`File not found: ${scriptUrl} (${response.status} ${response.statusText}). Make sure the file exists and is accessible.`);
714
737
  }
715
- // Criar e carregar novo script
716
- const script = document.createElement('script');
717
- script.src = scriptUrl;
718
- script.async = false; // Carregar de forma síncrona para garantir ordem
719
- script.type = 'text/javascript';
720
- script.onload = () => {
721
- // Aguardar um pouco para garantir que o objeto global foi criado
722
- setTimeout(() => {
723
- if (typeof window.OggVorbisEncoder !== 'undefined') {
724
- resolve();
725
- }
726
- else {
727
- reject(new Error('OggVorbisEncoder object not found after script load. The script may not have exported the global correctly.'));
728
- }
729
- }, 200);
730
- };
731
- script.onerror = (event) => {
732
- const error = new Error(`Failed to load OggVorbisEncoder script from ${scriptUrl}. Check browser console for CORS or network errors.`);
733
- console.error('Script load error:', event);
734
- console.error('Script URL:', scriptUrl);
735
- reject(error);
736
- };
737
- document.head.appendChild(script);
738
+ // Verificar Content-Type
739
+ const contentType = response.headers.get('content-type') || '';
740
+ if (!contentType.includes('javascript') && !contentType.includes('application/javascript') && !contentType.includes('text/javascript')) {
741
+ console.warn(`Warning: Content-Type is "${contentType}", expected JavaScript. Proceeding with validation...`);
742
+ }
743
+ // Verificar se o conteúdo é JavaScript (não HTML)
744
+ return response.text().then(text => {
745
+ const trimmedText = text.trim();
746
+ // Se começar com '<', provavelmente é HTML (erro 404, etc)
747
+ if (trimmedText.startsWith('<')) {
748
+ const errorMsg = `Invalid response from ${scriptUrl}. Expected JavaScript but received HTML (likely a 404 error page).\n\n` +
749
+ `The file was not found at this path. Please:\n` +
750
+ `1. Verify the file exists at: ${scriptUrl}\n` +
751
+ `2. Check if you need to copy files to your public/ folder\n` +
752
+ `3. Ensure your server is configured to serve the file\n` +
753
+ `4. Try accessing the URL directly in your browser`;
754
+ console.error(errorMsg);
755
+ reject(new Error(errorMsg));
756
+ return; // Não continuar se for HTML
757
+ }
758
+ // Verificar se parece com JavaScript (contém pelo menos algumas palavras-chave comuns)
759
+ if (!trimmedText.includes('function') && !trimmedText.includes('var') && !trimmedText.includes('const') && !trimmedText.includes('let')) {
760
+ console.warn(`Warning: Response from ${scriptUrl} does not appear to be valid JavaScript.`);
761
+ }
762
+ // Criar e carregar novo script
763
+ const script = document.createElement('script');
764
+ script.src = scriptUrl;
765
+ script.async = false; // Carregar de forma síncrona para garantir ordem
766
+ script.type = 'text/javascript';
767
+ script.onload = () => {
768
+ // Aguardar um pouco para garantir que o objeto global foi criado
769
+ setTimeout(() => {
770
+ if (typeof window.OggVorbisEncoder !== 'undefined') {
771
+ resolve();
772
+ }
773
+ else {
774
+ reject(new Error(`OggVorbisEncoder object not found after script load from ${scriptUrl}. The script may not have exported the global correctly, or the file may be corrupted.`));
775
+ }
776
+ }, 200);
777
+ };
778
+ script.onerror = (event) => {
779
+ const error = new Error(`Failed to load OggVorbisEncoder script from ${scriptUrl}. Check browser console for CORS or network errors. Make sure the file exists and is accessible.`);
780
+ console.error('Script load error:', event);
781
+ console.error('Script URL:', scriptUrl);
782
+ console.error('Try accessing the URL directly in your browser to verify it exists.');
783
+ reject(error);
784
+ };
785
+ document.head.appendChild(script);
786
+ });
738
787
  })
739
788
  .catch(error => {
740
- reject(new Error(`Cannot access OggVorbisEncoder script at ${scriptUrl}: ${error.message}`));
789
+ const errorMsg = `Cannot access OggVorbisEncoder script at ${scriptUrl}: ${error.message}\n\n` +
790
+ `Troubleshooting:\n` +
791
+ `1. Open ${scriptUrl} in your browser to verify the file exists\n` +
792
+ `2. Check browser console for CORS errors\n` +
793
+ `3. Ensure your server is configured to serve files from node_modules or public folder\n` +
794
+ `4. See TROUBLESHOOTING_ENCODER.md for more help`;
795
+ console.error(errorMsg);
796
+ reject(new Error(errorMsg));
741
797
  });
742
798
  });
743
799
  }
@@ -865,38 +921,71 @@
865
921
  });
866
922
  return;
867
923
  }
868
- // Primeiro, verificar se o arquivo existe fazendo uma requisição HEAD
869
- fetch(scriptUrl, { method: 'HEAD', cache: 'no-cache' })
924
+ // Verificar se o arquivo existe e é JavaScript válido
925
+ fetch(scriptUrl, { method: 'GET', cache: 'no-cache' })
870
926
  .then(response => {
871
927
  if (!response.ok) {
872
- throw new Error(`File not found: ${scriptUrl} (${response.status})`);
928
+ throw new Error(`File not found: ${scriptUrl} (${response.status} ${response.statusText}). Make sure the file exists and is accessible.`);
873
929
  }
874
- // Criar e carregar novo script
875
- const script = document.createElement('script');
876
- script.src = scriptUrl;
877
- script.async = false; // Carregar de forma síncrona para garantir ordem
878
- script.type = 'text/javascript';
879
- script.onload = () => {
880
- // Aguardar um pouco para garantir que o objeto global foi criado
881
- setTimeout(() => {
882
- if (typeof window.Mp3LameEncoder !== 'undefined') {
883
- resolve();
884
- }
885
- else {
886
- reject(new Error('Mp3LameEncoder object not found after script load. The script may not have exported the global correctly.'));
887
- }
888
- }, 200);
889
- };
890
- script.onerror = (event) => {
891
- const error = new Error(`Failed to load Mp3LameEncoder script from ${scriptUrl}. Check browser console for CORS or network errors.`);
892
- console.error('Script load error:', event);
893
- console.error('Script URL:', scriptUrl);
894
- reject(error);
895
- };
896
- document.head.appendChild(script);
930
+ // Verificar Content-Type
931
+ const contentType = response.headers.get('content-type') || '';
932
+ if (!contentType.includes('javascript') && !contentType.includes('application/javascript') && !contentType.includes('text/javascript')) {
933
+ console.warn(`Warning: Content-Type is "${contentType}", expected JavaScript. Proceeding with validation...`);
934
+ }
935
+ // Verificar se o conteúdo é JavaScript (não HTML)
936
+ return response.text().then(text => {
937
+ const trimmedText = text.trim();
938
+ // Se começar com '<', provavelmente é HTML (erro 404, etc)
939
+ if (trimmedText.startsWith('<')) {
940
+ const errorMsg = `Invalid response from ${scriptUrl}. Expected JavaScript but received HTML (likely a 404 error page).\n\n` +
941
+ `The file was not found at this path. Please:\n` +
942
+ `1. Verify the file exists at: ${scriptUrl}\n` +
943
+ `2. Check if you need to copy files to your public/ folder\n` +
944
+ `3. Ensure your server is configured to serve the file\n` +
945
+ `4. Try accessing the URL directly in your browser`;
946
+ console.error(errorMsg);
947
+ reject(new Error(errorMsg));
948
+ return; // Não continuar se for HTML
949
+ }
950
+ // Verificar se parece com JavaScript (contém pelo menos algumas palavras-chave comuns)
951
+ if (!trimmedText.includes('function') && !trimmedText.includes('var') && !trimmedText.includes('const') && !trimmedText.includes('let')) {
952
+ console.warn(`Warning: Response from ${scriptUrl} does not appear to be valid JavaScript.`);
953
+ }
954
+ // Criar e carregar novo script
955
+ const script = document.createElement('script');
956
+ script.src = scriptUrl;
957
+ script.async = false; // Carregar de forma síncrona para garantir ordem
958
+ script.type = 'text/javascript';
959
+ script.onload = () => {
960
+ // Aguardar um pouco para garantir que o objeto global foi criado
961
+ setTimeout(() => {
962
+ if (typeof window.Mp3LameEncoder !== 'undefined') {
963
+ resolve();
964
+ }
965
+ else {
966
+ reject(new Error(`Mp3LameEncoder object not found after script load from ${scriptUrl}. The script may not have exported the global correctly, or the file may be corrupted.`));
967
+ }
968
+ }, 200);
969
+ };
970
+ script.onerror = (event) => {
971
+ const error = new Error(`Failed to load Mp3LameEncoder script from ${scriptUrl}. Check browser console for CORS or network errors. Make sure the file exists and is accessible.`);
972
+ console.error('Script load error:', event);
973
+ console.error('Script URL:', scriptUrl);
974
+ console.error('Try accessing the URL directly in your browser to verify it exists.');
975
+ reject(error);
976
+ };
977
+ document.head.appendChild(script);
978
+ });
897
979
  })
898
980
  .catch(error => {
899
- reject(new Error(`Cannot access Mp3LameEncoder script at ${scriptUrl}: ${error.message}`));
981
+ const errorMsg = `Cannot access Mp3LameEncoder script at ${scriptUrl}: ${error.message}\n\n` +
982
+ `Troubleshooting:\n` +
983
+ `1. Open ${scriptUrl} in your browser to verify the file exists\n` +
984
+ `2. Check browser console for CORS errors\n` +
985
+ `3. Ensure your server is configured to serve files from node_modules or public folder\n` +
986
+ `4. See TROUBLESHOOTING_ENCODER.md for more help`;
987
+ console.error(errorMsg);
988
+ reject(new Error(errorMsg));
900
989
  });
901
990
  });
902
991
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-audio-recorder-ts",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "type": "module",
5
5
  "description": "TypeScript port of web-audio-recorder-js with full type support for WAV, OGG Vorbis, and MP3 audio recording",
6
6
  "main": "dist/index.cjs.js",