Uncaught ReferenceError: monaco is not defined at new t.MonacoWorkspace - undefined-reference

I just build the sample in the example folder (with some modifications to make monaco edit typescript rather json(I'm getting to know how to use monaco api), below in the post) but I got some erros on the console window like below and the autcompleter isn't working, only the syntax highlight.
The error is:
Uncaught ReferenceError: monaco is not defined
at new MonacoWorkspace (main.bundle.js:157068)
at create (main.bundle.js:157028)
at Object.install (main.bundle.js:157034)
at Object../lib/client.js (main.bundle.js:2132)
at __webpack_require__ (main.bundle.js:64)
at Object../lib/main.js (main.bundle.js:2202)
at __webpack_require__ (main.bundle.js:64)
at main.bundle.js:199
at main.bundle.js:202
Uncaught (in promise) Error: Unexpected usage
at EditorSimpleWorker.loadForeignModule (:4200/editor.worker.bundle.js:8995)
at SimpleWorkerServer._handleMessage (:4200/editor.worker.bundle.js:6629)
at Object.handleMessage (:4200/editor.worker.bundle.js:6615)
at SimpleWorkerProtocol._handleMessage (:4200/editor.worker.bundle.js:6484)
at SimpleWorkerProtocol.handleMessage (:4200/editor.worker.bundle.js:6457)
at SimpleWorkerServer.onmessage (:4200/editor.worker.bundle.js:6619)
at self.onmessage (:4200/editor.worker.bundle.js:10166)
the modified client and server goes like this:
client.ts
import { listen, MessageConnection } from 'vscode-ws-jsonrpc';
import * as monaco from 'monaco-editor'
import {
MonacoLanguageClient, CloseAction, ErrorAction,
MonacoServices, createConnection
} from 'monaco-languageclient';
import normalizeUrl = require('normalize-url');
const ReconnectingWebSocket = require('reconnecting-websocket');
// register Monaco languages
monaco.languages.register({
id: 'typescript',
extensions: ['.ts'],
aliases: ['TypeScript','ts','TS','Typescript','typescript']
})
// create Monaco editor
const value = `
let message:string = 'foo'
`;
monaco.editor.create(document.getElementById("container")!, {
model: monaco.editor.createModel(value, 'typescript', monaco.Uri.parse('file:///C:\\Users\\foo\\Desktop\\project\\demo\\ts\\file.ts')),
glyphMargin: true,
theme: "vs-dark",
lightbulb: {
enabled: true
}
});
// install Monaco language client services
MonacoServices.install(monaco)
// create the web socket
const url = createUrl('ws://localhost:3000/ws')
const webSocket = createWebSocket(url);
// listen when the web socket is opened
listen({
webSocket,
onConnection: connection => {
// create and start the language client
const languageClient = createLanguageClient(connection);
const disposable = languageClient.start();
connection.onClose(() => disposable.dispose());
}
});
function createLanguageClient(connection: MessageConnection): MonacoLanguageClient {
return new MonacoLanguageClient({
name: "Sample Language Client",
clientOptions: {
// use a language id as a document selector
documentSelector: ['typescript'],
// disable the default error handler
errorHandler: {
error: () => ErrorAction.Continue,
closed: () => CloseAction.DoNotRestart
}
},
// create a language client connection from the JSON RPC connection on demand
connectionProvider: {
get: (errorHandler, closeHandler) => {
return Promise.resolve(createConnection(connection, errorHandler, closeHandler))
}
}
});
}
function createUrl(path: string): string {
return normalizeUrl(path);
}
function createWebSocket(url: string): WebSocket {
const socketOptions = {
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 10000,
maxRetries: Infinity,
debug: false
};
return new ReconnectingWebSocket(url, [], socketOptions);
}
server.ts
import * as express from "express";
const app = express();
app.use(express.static(__dirname));
app.listen(4200)

Related

apollo explorer say "isTrusted": true when i try use Subscription

guys, I have a problem when I want to use a Subscription I'm facing this issue I don't find a solution in any place, I'm a GQL user and i decide to use Subscription to make real-time website but I'm facing a a this issue ,
hare is code
I'm trying to show apollo docs but I'm facing another issue(graphql doesn't find my resolver), so I try to use this pace of code in my mind it's work but the issue is it says
Unable to connect wss://localhost:4001 also I'm trying to use Unable to connect wss://localhost:4001/graphql and Unable to connect wss://localhost:4001/subscription, also i try this three way with using ws
// my resolver
const somethingChanged = () => {
// subscribe: () => {
console.log("subscribe")
pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC)
// }
}
const makeId = () => {
// make id generator 36 symbols
let id = Math.random().toString(36).split(".")[1]
pubsub.publish(SOMETHING_CHANGED_TOPIC, {
somethingChanged: {
id,
},
})
return id
}
const resolvers = {
Subscription: {
somethingChanged,
},
Query: {
hello: () => "Hello world!",
},
Mutation: {
makeId,
},
}
// app.ts
import { createServer } from "http"
import express from "express"
import { ApolloServer, gql } from "apollo-server-express"
import { typeDefs } from "./graphql/schema"
import "colors"
import resolvers from "./graphql/root"
import connect from "./db/connect"
import { PubSub } from "graphql-subscriptions"
const SOMETHING_CHANGED_TOPIC = "something_changed"
require("dotenv").config()
export const pubsub = new PubSub()
// 1 creating one function for app
const startServer = async () => {
// 2 // declaring app as express
const app = express()
const httpServer = createServer(app)
setInterval(() => {
console.log(`Server was work ${Math.random().toString()}`.green)
}, 2000)
// middleware's
connect()
// 5
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => req,
})
// 6
await apolloServer.start()
// 7
apolloServer.applyMiddleware({
app,
path: "/graphql",
})
// 8
httpServer.listen({ port: process.env.PORT || 4001 }, () =>
console.log(
`Server listening on localhost:4001${apolloServer.graphqlPath}`.blue
)
)
}
startServer()
I just want to test in apollo explorer but it doesn't work

Could anyone provide a fastapi websocket endpoint which could connect with the example given for RTK Query streaming updates

I'm trying to get my head around RTK Query as it applies to websockets. The example given is
import { createApi, fetchBaseQuery } from '#reduxjs/toolkit/query/react'
import { createEntityAdapter, EntityState } from '#reduxjs/toolkit'
import { isMessage } from './schemaValidators'
export type Channel = 'redux' | 'general'
export interface Message {
id: number
channel: Channel
userName: string
text: string
}
const messagesAdapter = createEntityAdapter<Message>()
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
endpoints: (build) => ({
getMessages: build.query<EntityState<Message>, Channel>({
query: (channel) => `messages/${channel}`,
transformResponse(response: Message[]) {
return messagesAdapter.addMany(
messagesAdapter.getInitialState(),
response
)
},
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved }
) {
const ws = new WebSocket('ws://localhost:8080')
try {
await cacheDataLoaded
const listener = (event: MessageEvent) => {
const data = JSON.parse(event.data)
if (!isMessage(data) || data.channel !== arg) return
updateCachedData((draft) => {
messagesAdapter.upsertOne(draft, data)
})
}
ws.addEventListener('message', listener)
} catch {}
await cacheEntryRemoved
ws.close()
},
}),
}),
})
export const { useGetMessagesQuery } = api
for the frontend. It looks as though the idea is to make a request to /messages/{channel} and on successful receipt and caching of these messages to connect to a websocket api. I'm struggling to create a fastapi app that connects with this example so I can figure out the workings. Does anyone have an example they might be willing to please share?

Redux saga failed in production

I've been trying to tackle this problem more than 2 weeks now. Everything works fine in development mode. But not in production mode. The example below are shown using Redux Saga environment (I'm still new in redux saga). But I've tried re-do it using Context API. Unfortunately the problem still persists. (below are the images showing successful process in development mode & unsuccessful process in production mode)
successful in development mode
unsuccessful in production mode
My guess it could be something to do with status code 304 Not Modified. Since the data I tried to fetch not changing, thus it will use cached data in browser. But I don't know how to setup my server so that I can handle this issue. I have read a bunch of online threads. But none were able to resolve my issue.
You may have a look at my code right now. Bear in mind that everything works just fine in development mode. From the images above you can see that I don't have problem logging in. Just fetching & getting data to be displayed in dashboard got error.
client/src/redux/actions/Dashboard.js (Action)
import { SET_ISDASHBOARD, SET_LOADING, SET_ERROR } from '../sagas/types'
// Set Loading
export const setLoading = (status) => ({
type: SET_LOADING,
payload: status
})
// Set Error
export const setError = (error) => ({
type: SET_ERROR,
payload: { error: error.status, message: error.message }
})
// Dashboard
export const isDashboard = () => ({
type: SET_ISDASHBOARD
})
client/src/redux/reducers/Dashboard.jd (Reducer)
import { SET_ERROR, SET_LOADING, SET_ISDASHBOARD, SET_DASHBOARD } from '../sagas/types'
const initialState = {
user: {
id: '',
name: '',
email: ''
},
loading: false,
error: false,
message: ''
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case SET_ISDASHBOARD:
return {
...state,
loading: true
}
case SET_DASHBOARD:
return {
...state,
user: {
...state.user,
id: action.payload.id,
email: action.payload.email,
name: action.payload.name
}
}
case SET_ERROR:
return {
...state,
error: action.payload.status,
message: action.payload.message
}
case SET_LOADING:
return {
...state,
loading: action.payload
}
default:
return state
}
}
export default reducer
client/src/redux/sagas/handlers/dashboard.js (Saga handlers)
import { call, put } from 'redux-saga/effects'
import { requestGetDashboard } from '../requests/dashboard'
import { SET_LOADING, SET_ERROR, SET_DASHBOARD } from '../types'
export function* handleGetDashboard(action) {
try {
const response = yield call(requestGetDashboard)
const result = response.data.data
console.log(response); console.log(result)
// dispatch set dashboard
yield put({ type: SET_DASHBOARD, payload: { id: result.id, email: result.email, name: result.name } })
} catch(error) {
// console.log(error); console.log(error.response)
const result = error.response.data
const payload = {
status: true,
message: result.error
}
// dispatch setError
yield put({ type: SET_ERROR, payload: payload })
}
// loading to false
yield put({ type: SET_LOADING, payload: false })
}
client/src/redux/sagas/requests/dashboard.js (Saga requests)
import axios from 'axios'
/** get dashboard */
export const requestGetDashboard = () => {
return axios.get(
'/api/v1/dashboard',
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('uid')}`
}
}
)
}
client/src/redux/sagas/rootSaga.js (Root Saga)
import {
SET_ISLOGIN, SET_ISLOGOUT, SET_ISAUTH,
SET_ISDASHBOARD,
} from './types'
import { takeLatest } from 'redux-saga/effects'
import { handleClientAuth, handlePostLogin, handlePostLogout } from './handlers/auth'
import { handleGetDashboard } from './handlers/dashboard'
export function* watcherSaga() {
// auth
yield takeLatest(SET_ISLOGIN, handlePostLogin)
yield takeLatest(SET_ISLOGOUT, handlePostLogout)
yield takeLatest(SET_ISAUTH, handleClientAuth)
// dashboard
yield takeLatest(SET_ISDASHBOARD, handleGetDashboard)
}
client/src/redux/sagas/types.js (Types)
/** for AUTH */
export const SET_ISLOGIN = 'SET_ISLOGIN'
export const SET_ISLOGOUT = 'SET_ISLOGOUT'
export const SET_ISAUTH = 'SET_ISAUTH'
export const SET_AUTH = 'SET_AUTH'
export const SET_LOADING = 'SET_LOADING'
export const SET_ERROR = 'SET_ERROR'
/** for DASHBOARD */
export const SET_ISDASHBOARD = 'SET_ISDASHBOARD'
export const SET_DASHBOARD = 'SET_DASHBOARD'
Please point me to any directions that could help get closer insight to this problem.

Heroku Error: ENOENT: no such file or directory, stat '/app/build/index.html'

I am getting this error in my heroku logs.
Same Question
All the solutions provided here did not address the issue.
I tried the different variations of the get method:
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
What else could I try or am I missing from here?
App.js
const configuration = require('#feathersjs/configuration');
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const socketio = require('#feathersjs/socketio');
const moment = require('moment');
class IdeaService {
constructor() {
this.ideas = [];
}
async find() {
return this.ideas;
}
async create(data) {
const idea = {
id: this.ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
this.ideas.push(idea);
return idea;
}
}
const app = express(feathers());
app.feathers().configure(configuration());
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
// Parse JSON
app.use(express.json());
// Configure SocketIO realtime API
app.configure(socketio());
// Enable REST services
app.configure(express.rest());
// Register services
app.use('/ideas', new IdeaService());
// Connect new streams
app.on('connection', conn => app.channel('stream').join(conn));
// Publish events to stream
app.publish(data => app.channel('stream'));
const PORT = process.env.PORT || 3030;
app.listen(PORT).on('listening', () => console.log(`Server running on port ${PORT}`));
app.service('ideas').create({
text: 'Build a cool app',
tech: 'Node.js',
viewer: 'John Doe'
});
export default IdeaService;
package.json

Socket IO with ReactNative

I try to use SocketIO in ReactNative by follow this link
https://github.com/facebook/react-native/issues/4393,
On IOS it work very well but Android it could not work
Result Of Socket Object
connected:false
index.android.js
window.navigator.userAgent = 'react-native';//'react-native';
const io = require('socket.io-client/socket.io');
export default class testApp extends Component {
componentWillMount(){
this.socket = io.connect('http://localhost:3000', {
jsonp: false,
transports: ['websocket']
});
// Socket Object connected:false
}
componentDidMount(){
console.log(this.socket)
this.socket.on('connect', () => {
console.log('ready to emit')
console.log('connected!');
});
}
package.json
"react-native": "0.35.0",
"socket.io-client": "^1.5.1"
I could not found similar problem
I missing something?
edited :
I'm not sure can I test socketIO in localhost with ReactNative but It's work when I test on IOS emulator
edited2 :
My fault It cannot test on local environment server
but It's work on IOS not android
Can Anybody Explained Why?
I also wanted to use Socket.IO with ExpressJS server and React Native but couldn't get it to work.
Then used https://facebook.github.io/react-native/docs/network.html#websocket-support with https://github.com/websockets/ws
And works great.
this FullExample for Socket.io in clint ( I Hope Work for you )
import React from 'react';
import SocketIOClient from 'socket.io-client'
const USER_ID = '#userId';
export default class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
userId: null
};
this.determineUser = this.determineUser.bind(this);
this.onReceivedMessage = this.onReceivedMessage.bind(this);
this.onSend = this.onSend.bind(this);
this._storeMessages = this._storeMessages.bind(this);
this.socket = SocketIOClient('http://localhost:3000');
this.socket.on('message', this.onReceivedMessage);
this.determineUser();
}
/**
* When a user joins the chatroom, check if they are an existing user.
* If they aren't, then ask the server for a userId.
* Set the userId to the component's state.
*/
determineUser() {
AsyncStorage.getItem(USER_ID)
.then((userId) => {
// If there isn't a stored userId, then fetch one from the server.
if (!userId) {
this.socket.emit('userJoined', null);
this.socket.on('userJoined', (userId) => {
AsyncStorage.setItem(USER_ID, userId);
this.setState({ userId });
});
} else {
this.socket.emit('userJoined', userId);
this.setState({ userId });
}
})
.catch((e) => alert(e));
}
// Event listeners
/**
* When the server sends a message to this.
*/
onReceivedMessage(messages) {
this._storeMessages(messages);
}
/**
* When a message is sent, send the message to the server
* and store it in this component's state.
*/
onSend(messages=[]) {
this.socket.emit('message', messages[0]);
this._storeMessages(messages);
}
render() {
var user = { _id: this.state.userId || -1 };
return (
<></>
);
}
}
const Local = Platform.OS === 'ios' ? 'http://localhost:3000' : 'http://10.0.2.2:3000'
import io from "socket.io-client";
//
this.socket = io(Local);
// console.log(this.socket)
this.socket.emit(Socket_category, Socket_online_subset);
this.socket.on(Socket_connection_name, this.onReceivedMessage);
onReceivedMessage =(messages)=> {consol,log(message)}
io.on('connection', function (client) {console.log('User Joined :)')
client.on(Path_Socket.Socket_category, function (room_name) {
console.log('joined room online ;) '+room_name);
client.join(room_name);
})
}
io.sockets.in(Socket_online_subset)
.emit(Socket_connection_name, data(any thing));
may be this will through error
import io from "socket.io-client/socket.io"
Then just add below line....
import io from "socket.io-client/dist/socket.io";
then in componentDidMount or useEffect function just add below line. Never use it under constructor of class component.
var socket = io("https://localhost.com:3000", { jsonp: false });
// client-side
socket.on("chat_message", (msg) => {
console.log(msg);
});

Resources