11import sqlite3InitModule from '@sqlite.org/sqlite-wasm' ;
22
3+ // Ensure BigInt values serialize properly in JSON.stringify without throwing TypeError
4+ if ( typeof BigInt !== 'undefined' && ! ( BigInt . prototype as any ) . toJSON ) {
5+ ( BigInt . prototype as any ) . toJSON = function ( ) {
6+ const n = Number ( this ) ;
7+ return Number . isSafeInteger ( n ) ? n : this . toString ( ) ;
8+ } ;
9+ }
10+
311export interface TableColumnInfo {
412 cid : number ;
513 name : string ;
@@ -720,8 +728,14 @@ export class SqliteEngine {
720728 static toCsv ( columns : string [ ] , rows : any [ ] [ ] ) : string {
721729 const escapeCell = ( val : any ) => {
722730 if ( val === null || val === undefined ) return '' ;
731+ if ( typeof val === 'bigint' ) return val . toString ( ) ;
732+ if ( val instanceof Uint8Array ) {
733+ return Array . from ( val )
734+ . map ( ( b ) => b . toString ( 16 ) . padStart ( 2 , '0' ) )
735+ . join ( '' ) ;
736+ }
723737 const str = String ( val ) ;
724- if ( str . includes ( ',' ) || str . includes ( '"' ) || str . includes ( '\n' ) ) {
738+ if ( str . includes ( ',' ) || str . includes ( '"' ) || str . includes ( '\n' ) || str . includes ( '\r' ) ) {
725739 return `"${ str . replace ( / " / g, '""' ) } "` ;
726740 }
727741 return str ;
@@ -743,7 +757,25 @@ export class SqliteEngine {
743757 } ) ;
744758 return obj ;
745759 } ) ;
746- return JSON . stringify ( objects , null , 2 ) ;
760+ return JSON . stringify (
761+ objects ,
762+ ( _key , value ) => {
763+ if ( typeof value === 'bigint' ) {
764+ // If within JS safe integer range, serialize as number so JSON parsers read it as number
765+ if ( value <= BigInt ( Number . MAX_SAFE_INTEGER ) && value >= BigInt ( Number . MIN_SAFE_INTEGER ) ) {
766+ return Number ( value ) ;
767+ }
768+ return value . toString ( ) ;
769+ }
770+ if ( value instanceof Uint8Array ) {
771+ return Array . from ( value )
772+ . map ( ( b ) => b . toString ( 16 ) . padStart ( 2 , '0' ) )
773+ . join ( '' ) ;
774+ }
775+ return value ;
776+ } ,
777+ 2
778+ ) ;
747779 }
748780
749781 /**
@@ -756,8 +788,11 @@ export class SqliteEngine {
756788 const lines = rows . map ( ( row ) => {
757789 const vals = row . map ( ( v ) => {
758790 if ( v === null || v === undefined ) return 'NULL' ;
759- if ( typeof v === 'number' ) return v ;
791+ if ( typeof v === 'number' || typeof v === 'bigint' ) return v . toString ( ) ;
760792 if ( typeof v === 'boolean' ) return v ? 1 : 0 ;
793+ if ( v instanceof Uint8Array ) {
794+ return `X'${ Array . from ( v ) . map ( ( b ) => b . toString ( 16 ) . padStart ( 2 , '0' ) ) . join ( '' ) } '` ;
795+ }
761796 return `'${ String ( v ) . replace ( / ' / g, "''" ) } '` ;
762797 } ) ;
763798 return `INSERT INTO "${ tableName } " (${ colList } ) VALUES (${ vals . join ( ', ' ) } );` ;
0 commit comments