Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix incorrect parsing/rounding of BigInt #920

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/SDK/Language/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,11 @@ public function getFiles(): array
'destination' => 'src/enums/{{ enum.name | caseDash }}.ts',
'template' => 'web/src/enums/enum.ts.twig',
],
[
'scope' => 'default',
'destination' => 'src/helper/json.ts',
'template' => 'web/src/helper/json.ts.twig',
],
];
}
}
5 changes: 5 additions & 0 deletions src/SDK/Language/Web.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ public function getFiles(): array
'destination' => 'src/enums/{{ enum.name | caseDash }}.ts',
'template' => 'web/src/enums/enum.ts.twig',
],
[
'scope' => 'default',
'destination' => 'src/helper/json.ts',
'template' => 'web/src/helper/json.ts.twig',
],
];
}

Expand Down
3 changes: 2 additions & 1 deletion templates/node/src/client.ts.twig
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fetch, FormData, File } from 'node-fetch-native-with-agent';
import { createAgent } from 'node-fetch-native-with-agent/agent';
import { Models } from './models';
import JsonBigInt from './helper/json';

type Payload = {
[key: string]: any;
Expand Down Expand Up @@ -170,7 +171,7 @@ class Client {
} else {
switch (headers['content-type']) {
case 'application/json':
options.body = JSON.stringify(params);
options.body = JsonBigInt.stringify(params);
break;

case 'multipart/form-data':
Expand Down
12 changes: 7 additions & 5 deletions templates/web/src/client.ts.twig
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Models } from './models';
import JsonBigInt from './helper/json';

/**
* Payload type representing a key-value pair with string keys and any values.
Expand Down Expand Up @@ -442,7 +443,7 @@ class Client {
},
onMessage: (event) => {
try {
const message: RealtimeResponse = JSON.parse(event.data);
const message: RealtimeResponse = JsonBigInt.parse(event.data);
this.realtime.lastMessage = message;
switch (message.type) {
case 'connected':
Expand All @@ -451,7 +452,7 @@ class Client {
const messageData = <RealtimeResponseConnected>message.data;

if (session && !messageData.user) {
this.realtime.socket?.send(JSON.stringify(<RealtimeRequest>{
this.realtime.socket?.send(JsonBigInt.stringify(<RealtimeRequest>{
type: 'authentication',
data: {
session
Expand Down Expand Up @@ -564,7 +565,7 @@ class Client {
} else {
switch (headers['content-type']) {
case 'application/json':
options.body = JSON.stringify(params);
options.body = JsonBigInt.stringify(params);
break;

case 'multipart/form-data':
Expand Down Expand Up @@ -644,19 +645,20 @@ class Client {
let data: any = null;

const response = await fetch(uri, options);
const responseData = await response.text();

const warnings = response.headers.get('x-{{ spec.title | lower }}-warning');
if (warnings) {
warnings.split(';').forEach((warning: string) => console.warn('Warning: ' + warning));
}

if (response.headers.get('content-type')?.includes('application/json')) {
data = await response.json();
data = JsonBigInt.parse(responseData)
} else if (responseType === 'arrayBuffer') {
data = await response.arrayBuffer();
} else {
data = {
message: await response.text()
message: responseData
};
}

Expand Down
46 changes: 46 additions & 0 deletions templates/web/src/helper/json.ts.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Helper class for JSON parsing/stringifying with `BigInt` support.
*/
export default class JsonBigInt {

// Preprocesses JSON to wrap large numbers in quotes.
static #preprocessJson(jsonString: string): string {
return jsonString.replaceAll(
/([:\s\[,]*)(-?\d+)([\s,\]]*)/g,
(match, prefix, num, suffix) =>
!Number.isSafeInteger(+num) ? `${prefix}"${num}"${suffix}` : match
);
}

/**
* Parses JSON, converting large numbers to `BigInt`.
*
* @param {string} jsonString - The JSON string.
* @returns {any} - The parsed object.
*/
static parse(jsonString: string): any {
const processedJsonString = this.#preprocessJson(jsonString);

return JSON.parse(processedJsonString, (key, value) => {
if (typeof value === 'string' && /^-?\d+$/.test(value)) {
return BigInt(value);
}
return value;
});
}

/**
* Stringifies an object, converting `BigInt` to strings.
*
* @param {object} obj - The object to stringify.
* @returns {string} - The JSON string.
*/
static stringify(obj: object): string {
return JSON.stringify(obj, (_, value) => {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
});
}
}
8 changes: 5 additions & 3 deletions templates/web/src/query.ts.twig
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import JsonBigInt from './helper/json';

type QueryTypesSingle = string | number | boolean;
export type QueryTypesList = string[] | number[] | boolean[] | Query[];
export type QueryTypes = QueryTypesSingle | QueryTypesList;
Expand Down Expand Up @@ -41,7 +43,7 @@ export class Query {
* @returns {string}
*/
toString(): string {
return JSON.stringify({
return JsonBigInt.stringify({
method: this.method,
attribute: this.attribute,
values: this.values,
Expand Down Expand Up @@ -248,7 +250,7 @@ export class Query {
* @returns {string}
*/
static or = (queries: string[]) =>
new Query("or", undefined, queries.map((query) => JSON.parse(query))).toString();
new Query("or", undefined, queries.map((query) => JsonBigInt.parse(query))).toString();

/**
* Combine multiple queries using logical AND operator.
Expand All @@ -257,5 +259,5 @@ export class Query {
* @returns {string}
*/
static and = (queries: string[]) =>
new Query("and", undefined, queries.map((query) => JSON.parse(query))).toString();
new Query("and", undefined, queries.map((query) => JsonBigInt.parse(query))).toString();
}