Skip to content

Commit

Permalink
Add Logging back from Sleeper app (#35)
Browse files Browse the repository at this point in the history
- Convert console.log statements to return messages from sleeper app
- Fix Windows Docker issue with recompiling
  • Loading branch information
sleeper-jasonl authored Aug 28, 2024
1 parent f565d55 commit c5a1779
Show file tree
Hide file tree
Showing 10 changed files with 192 additions and 120 deletions.
8 changes: 2 additions & 6 deletions bin/build_mini.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,10 @@ const getCommands = (projectName) => {
const zip = isWindows ?
`powershell Compress-Archive -Path "${distPath}" -DestinationPath "${zipFilePath}"` :
`cd dist && zip -r "${projectName}.zip" * && cd -`;
const openFile = isWindows ? `start dist` : `open dist`;
const cleanIndex = `${removeDir} "${bundleOutputPath["ios"]}" "${bundleOutputPath["android"]}" "${sourcemapOutputPath["ios"]}" "${sourcemapOutputPath["android"]}"`;
const cleanAll = `${removeDir} dist node_modules`;
const cleanBuild = `${removeDir} "${distPath}" "${assetsDestPath["ios"]}" "${assetsDestPath["android"]}"`;
const install = `yarn install && cd ios && pod install && cd -`;
const install = `yarn install`;

const getBundleCommand = (platform) => {
return `node "${reactNativeCliPath}" webpack-bundle \
Expand All @@ -56,7 +55,6 @@ const getCommands = (projectName) => {
bundleIOS: getBundleCommand('ios'),
bundleAndroid: getBundleCommand('android'),
zip,
openFile,
cleanIndex,
cleanAll,
cleanBuild,
Expand Down Expand Up @@ -159,7 +157,7 @@ const main = async () => {
// Clean build folders
await spawnProcess(commands.cleanAll, "clean command exited with non-zero code");

// Run yarn + pod install
// Run yarn
await spawnProcess(commands.install, "install command exited with non-zero code");
}

Expand All @@ -185,8 +183,6 @@ const main = async () => {
// Clean build folders
await spawnProcess(commands.cleanBuild, "clean build command exited with non-zero code");

// Open output folder
await spawnProcess(commands.openFile);
process.exit(0);
};

Expand Down
5 changes: 3 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as Sleeper from './src/components';
import DevServer from './src/dev_server';
import * as Types from './src/types';
import {Fonts, Theme} from './src/styles';
import { Fonts, Theme } from './src/styles';
import MiniLogger from './src/components/MiniLogger';

export {Sleeper, DevServer, Types, Fonts, Theme};
export { Sleeper, DevServer, Types, Fonts, Theme, MiniLogger };
5 changes: 2 additions & 3 deletions mini_packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"@notifee/react-native": "7.8.0",
"@ptomasroos/react-native-multi-slider": "2.2.2",
"@react-native-camera-roll/camera-roll": "5.2.0",
"@react-native-community/blur": "3.6.0",
"@react-native-community/blur": "4.3.2",
"@react-native-community/datetimepicker": "2.6.2",
"@react-native-community/hooks": "2.8.0",
"@react-native-community/netinfo": "9.3.7",
Expand All @@ -17,7 +17,7 @@
"@react-navigation/native": "6.1.3",
"@react-navigation/stack": "6.3.12",
"@shopify/flash-list": "1.4.1",
"@sleeperhq/mini-core": "1.9.2",
"@sleeperhq/mini-core": "1.9.8",
"amazon-cognito-identity-js": "6.3.2",
"crypto-js": "3.3.0",
"decimal.js-light": "2.5.1",
Expand All @@ -30,7 +30,6 @@
"react-native": "0.72.14",
"react-native-action-sheet": "2.2.0",
"react-native-animatable": "1.3.3",
"react-native-branch": "5.4.0",
"react-native-check-version": "1.0.20",
"react-native-color-matrix-image-filters": "5.2.10",
"react-native-compressor": "1.5.2",
Expand Down
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sleeperhq/mini-core",
"version": "1.9.2",
"version": "1.9.8",
"description": "Core library frameworks for developing Sleeper Mini Apps.",
"main": "index.ts",
"types": "index.d.ts",
Expand Down Expand Up @@ -43,20 +43,21 @@
"@react-native-community/netinfo": "9.3.7",
"axios": "0.15.3",
"babel-loader": "9.1.2",
"react-native-fast-image": "https://github.com/blitzstudios/react-native-fast-image.git#release/1.1",
"react-native-fast-image": "https://github.com/blitzstudios/react-native-fast-image.git#release/1.2",
"react-native-interactable": "https://github.com/blitzstudios/react-native-interactable#release/1.1",
"react-native-linear-gradient": "2.5.6",
"react-native-rename": "^3.2.12",
"react-refresh": "0.14.0",
"react-test-renderer": "17.0.2",
"regenerator-runtime": "0.13.11",
"rx": "4.1.0",
"string-replace-loader": "3.1.0",
"terser-webpack-plugin": "5.3.6",
"webpack": "5.75.0"
},
"peerDependencies": {
"react": "18.2.0",
"react-native": "0.72.14",
"react-native-svg": "13.7.0"
"react-native-svg": "13.14.0"
},
"devDependencies": {
"@babel/core": "7.15.8",
Expand Down
79 changes: 79 additions & 0 deletions src/common/packet_parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
class PacketParser {
constructor(props) {
this.logsEnabled = props.logsEnabled || false;
this.messageLength = 0;
this.messageType = '';
this.messageLength = 0;
this.partialMessage = '';
this.onMessageRecieved = props.onMessageRecieved;
}

parseMessage(msgString) {
while (msgString.length > 0) {
if (this.messageLength === 0) {
const delimit = msgString.indexOf('\n');
if (delimit === -1) {
console.log("[Sleeper] Message header not found, throwing out message.");
return;
}

const header = msgString.substring(0, delimit);
try {
const headerObject = JSON.parse(header);
this.messageType = headerObject.type;
this.messageLength = headerObject.size;
} catch (e) {
console.log("[Sleeper] Message header malformed, throwing out message.");
this.messageLength = 0;
this.messageType = '';
return;
}

msgString = msgString.substring(delimit + 1);
}

const partialLength = this.messageLength - this.partialMessage.length;
if (partialLength < 0) {
// We need to wait for more data
this.partialMessage += msgString;
return;
}

const remainingLength = msgString.length - partialLength;
if (remainingLength === 0) {
// We have the full message
this.partialMessage += msgString;
msgString = '';
if (this.logsEnabled) console.log("[Sleeper] Message built.", this.partialMessage.length);

} else {
// We have more than the full message
this.partialMessage += msgString.substring(0, partialLength);
msgString = msgString.substring(partialLength);

if (remainingLength <= 0) {
// We have less than the full message
if (this.logsEnabled) console.log("[Sleeper] Building message: ", this.partialMessage.length, this.messageLength, remainingLength);
return;
}
}

try {
const json = JSON.parse(this.partialMessage);
this.partialMessage = '';
this.messageLength = 0;

this.onMessageRecieved({
type: this.messageType,
data: json,
});
} catch (e) {
console.log("[Sleeper] Failed to parse message: ", e);
return;
}
}
}

};

module.exports = PacketParser;
18 changes: 18 additions & 0 deletions src/components/MiniLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Rx from 'rx';

class MiniLogger {
public static messages = new Rx.Subject;

static log(...args: any[]) {
this.messages.onNext({
type: 'mini_dev_server',
action: 'onConsoleLog',
message: Array.from(args).join(' '),
});
}
}

// Add global function for mini logging
global.log_mini = (...args: any[]) => { MiniLogger.log(...args); }

export default MiniLogger;
140 changes: 41 additions & 99 deletions src/dev_server/index.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import React, {useEffect, useRef, useState} from 'react';
import {Platform, NativeModules} from 'react-native';
import {Config, SocketMessage} from '../types';
import React, { useEffect, useRef, useState } from 'react';
import { Platform } from 'react-native';
import { Config, SocketMessage } from '../types';
import { ScriptLocatorResolver, ScriptManager } from '@callstack/repack/client';
import NetInfo, { NetInfoState } from '@react-native-community/netinfo';
import TcpSocket from 'react-native-tcp-socket';
import { fetchMainVersionMap, getMainUrl } from './url_resolver';
import PacketParser from '../common/packet_parser';

let config: Config;
const RETRY_TIMER = 5000;

const DevServer = props => {
const connection = useRef<TcpSocket.Socket>();
const partialMessage = useRef('');
const messageLength = useRef(0);
const messageType = useRef('');
const _retryTimer = useRef<NodeJS.Timeout>();
const packetParser = useRef<PacketParser>();

const [data, setData] = useState({
platform: '',
Expand All @@ -29,92 +28,6 @@ const DevServer = props => {
props.onConnected(value);
};

const onSocket = (handler) => msg => {
let msgString: string = msg.toString();
while (msgString.length > 0) {
if (messageLength.current === 0) {
const delimit = msgString.indexOf('\n');
if (delimit === -1) {
console.log("[Sleeper] Message header not found, throwing out message.");
return;
}

const header = msgString.substring(0, delimit);
try {
const headerObject = JSON.parse(header);
messageType.current = headerObject.type;
messageLength.current = headerObject.size;
} catch (e) {
console.log("[Sleeper] Message header malformed, throwing out message.");
messageLength.current = 0;
messageType.current = '';
return;
}

msgString = msgString.substring(delimit + 1);
}

const partialLength = messageLength.current - partialMessage.current.length;
if (partialLength < 0) {
// We need to wait for more data
partialMessage.current += msgString;
return;
}

const remainingLength = msgString.length - partialLength;
if (remainingLength === 0) {
// We have the full message
partialMessage.current += msgString;
msgString = '';
if (config.logsEnabled) console.log("[Sleeper] Message built.", partialMessage.current.length);

} else {
// We have more than the full message
partialMessage.current += msgString.substring(0, partialLength);
msgString = msgString.substring(partialLength);

if (remainingLength <= 0) {
// We have less than the full message
if (config.logsEnabled) console.log("[Sleeper] Building message: ", partialMessage.current.length, messageLength.current, remainingLength);
return;
}
}

try {
const json = JSON.parse(partialMessage.current);
partialMessage.current = '';
messageLength.current = 0;

// Set connection data
if (json._platform || json._binaryVersion || json._dist || json._isStaging) {
if (config.logsEnabled) console.log("[Sleeper] Processing context data:", json._platform, json._binaryVersion, json._dist, json._isStaging);
setData({
platform: json._platform,
binaryVersion: json._binaryVersion,
dist: json._dist,
isStaging: json._isStaging,
});
}

if (messageType.current === 'context') {
// We should have a context object now
const context = new Proxy(json._context, handler);
props.onContextChanged(context, json._entitlements);
} else if (messageType.current === `partialContext`) {
// We are updating a partial Context
props.onContextUpdated(json._context);
} else if (messageType.current === 'entitlements') {
props.onEntitlementsUpdated(json._entitlements);
}

messageType.current = '';
} catch (e) {
console.log("[Sleeper] Failed to parse message: ", e);
return;
}
}
};

const sendContextRequest = (socket, propertyPath) => {
const message: SocketMessage = {_contextGet: propertyPath};
const json = JSON.stringify(message);
Expand Down Expand Up @@ -187,9 +100,35 @@ const DevServer = props => {
// @ts-ignore
const ipAddress = netInfoDetails?.ipAddress;

const scriptURL = NativeModules.SourceCode.scriptURL;
const address = scriptURL.split('://')[1].split('/')[0];
const packagerIP = address.split(':')[0];
const createPacketParser = (handler) => {
return new PacketParser({
logsEnabled: false,
onMessageRecieved: (msg) => {
const json = msg.data;
// Set connection data
if (json._platform || json._binaryVersion || json._dist || json._isStaging) {
if (config.logsEnabled) console.log("[Sleeper] Processing context data:", json._platform, json._binaryVersion, json._dist, json._isStaging);
setData({
platform: json._platform,
binaryVersion: json._binaryVersion,
dist: json._dist,
isStaging: json._isStaging,
});
}

if (msg.type === 'context') {
// We should have a context object now
const context = new Proxy(json._context, handler);
props.onContextChanged(context, json._entitlements);
} else if (msg.type === `partialContext`) {
// We are updating a partial Context
props.onContextUpdated(json._context);
} else if (msg.type === 'entitlements') {
props.onEntitlementsUpdated(json._entitlements);
}
}
});
};

if (!netInfoDetails || !('ipAddress' in netInfoDetails)) {
console.error('[Sleeper] Failed to determine local IP address.');
Expand All @@ -203,15 +142,17 @@ const DevServer = props => {
reuseAddress: true,
}, () => {
console.log('[Sleeper] Connected to the Sleeper App.');
const handler = proxyHandler(connection.current);
packetParser.current = createPacketParser(handler);

// When we establish a connection, request context
sendContextRequest(connection.current, "");
_onConnected(true);
});

connection.current.on('data', (data, ...args) => {
const handler = proxyHandler(connection.current);
const onSocketHandler = onSocket(handler);
onSocketHandler(data);
connection.current.on('data', (data) => {
const msgString: string = data.toString();
packetParser.current?.parseMessage(msgString);
});
connection.current.on('error', err => {
return stopSocket();
Expand All @@ -223,6 +164,7 @@ const DevServer = props => {

const stopSocket = (retry = true) => {
_onConnected(false);
packetParser.current = undefined;

if (connection.current) {
connection.current.destroy();
Expand Down
Loading

0 comments on commit c5a1779

Please sign in to comment.