I already have a popup page with class name #popup that I would like it to open on leave mouse, only one time per session. I don’t know how to write the script code that I would like to insert on on the homepage.
Thank you in advance.
Chris
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I already have a popup page with class name #popup that I would like it to open on leave mouse, only one time per session. I don’t know how to write the script code that I would like to insert on on the homepage.
Thank you in advance.
Chris
I am using formvalidation.io to validate my form.
but I have a problem in validating image files and pdf files in one input.
try changing it here
fields: {
fileupload: {
validators: {
file: {
extension: 'jpeg,jpg,png,pdf',
type: 'image/jpeg, image/png, application/pdf',
maxSize: 5 * 1024 * 1024, // 5 MB
message: 'The selected file is not valid, it should be (jpeg,jpg,png,pdf) and 5 MB at maximum.'
}
}
}
}
with a format like that.
it can only upload jpg files, am I doing something wrong ?
I am very new to Javascript and HTML. So I don’t really know how to format my google searches to give me the answer I am looking for. However I did try and I have this code below.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>Trivia!</title>
<script>
var buttonClicked = null;
function freeFormCheck(){
const answerInput = document.getElementById('answer').value
let header = document.querySelector("#part2");
if(answerInput === "Edinburgh"){
header.innerText = "Correct answer!";
}else{
header.innerText = "Wrong answer!";
}
}
function validationButton(id){
if(buttonClicked != null){
buttonClicked.style.background = "#d9edff";
};
buttonClicked = document.getElementById(id);
let header = document.querySelector("#part1");
switch(id){
case "correct":
buttonClicked.style.background = "green";
header.innerText = "Correct answer!";
break;
case "one":
buttonClicked.style.background = "red";
header.innerText = "Wrong answer!";
break;
case "two":
buttonClicked.style.background = "red";
header.innerText = "Wrong answer!";
break;
case "three":
buttonClicked.style.background = "red";
header.innerText = "Wrong answer!";
break;
}
}
</script>
</head>
<body>
<div class="header">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<h3>On average, statistically: how many men die every hour?</h3>
<h3 id="part1"></h3>
<button onClick=validationButton(id) id="correct">1 per hour</button>
<button onClick=validationButton(id) id="one">0.5 per hour ( 1 per 2 hour)</button>
<button onClick=validationButton(id) id="two">less than 1 per hour</button>
<button onClick=validationButton(id) id="three">0.25 per hour</button>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<h3>What used to be the capital of Scotland</h3>
<h3 id="part2"></h3>
<form>
<lable for="answer">Enter here:</lable>
<input type="text" id="answer"><br>
<input for="answer" type="button" onClick=freeFormCheck()>
</form>
</div>
</div>
</body>
</html>
This is a whole chunk of code so I will list the problem below with the relevant code:
For context: I am suppose to ask a question where the user inputs a response and then I have to check if it is the right answer.
Here is the html part:
<h3>What used to be the capital of Scotland</h3>
<h3 id="part2"></h3>
<form>
<lable for="answer">Enter here:</lable>
<input type="text" id="answer"><br>
<input for="answer" type="button" onClick=freeFormCheck()>
</form>
And here is the java script for freeFormCheck():
function freeFormCheck(){
const answerInput = document.getElementById('answer').value
let header = document.querySelector("#part2");
if(answerInput === "Edinburgh"){
header.innerText = "Correct answer!";
}else{
header.innerText = "Wrong answer!";
}
}
So to my understanding and some google researches, document.getElementById().value should’ve returned and stored the user input in the constant called answerInput.
This then should’ve been compared in the if statement.
I know for sure the header part works because it worked in the other javascript function.
Can anyone help?
I created this custom mapbox style to use in leaflet OR as a base map in tableau and it doesn’t work in either.
Here is my style’s preview link: https://api.mapbox.com/styles/v1/jbuell2024/clzlwunn0003701r83gbo30zp.html?title=view&access_token=pk.eyJ1IjoiamJ1ZWxsMjAyNCIsImEiOiJjbHpsdXJoMnMwNnRyMnZwd3hseXBkZnJyIn0.LhvNTpWqA389pQTriiNB7A&zoomwheel=true&fresh=true#5.92/36.758/-118.037
Here is the style URL: mapbox://styles/jbuell2024/clzlwunn0003701r83gbo30zp
Here is the basic leaflet code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leaflet Map with Mapbox Layer</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<style>
#map {
height: 100vh;
width: 100vw;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script>
// Initialize the map centered on a specific location
var map = L.map('map').setView([37, -119.0187], 6);
// Add Mapbox style layer to the map
L.tileLayer('https://api.mapbox.com/styles/v1/jbuell2024/clzlwunn0003701r83gbo30zp/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiamJ1ZWxsMjAyNCIsImEiOiJjbHpsdXJoMnMwNnRyMnZwd3hseXBkZnJyIn0.LhvNTpWqA389pQTriiNB7A', {
attribution: 'Map data © <a href="https://www.mapbox.com/about/maps/">Mapbox</a> contributors',
minZoom: 0,
maxZoom: 22
}).addTo(map);
</script>
</body>
</html>
Where am I going wrong?
I have tried testing my access token to ensure that is not the issue via replacing my style ID with a generic mapbox ID and the generic mapbox style loads correctly, so it’s not an issue of my access token. When I test the leaflet code, all there is is a grey screen.
I’m going through the odin project right now and am almost done with the tic tac toe project but I’m stuck on making the reset button. It will get rid of the x’s and o’s from the board array and on the screen but you cannot play the game any more after. Here is a codepen for my project: https://codepen.io/Jibbberish/pen/BagdVey
const reset = document.querySelector(".reset");
reset.addEventListener("click", () => {
makeGameboard.gameboard = [null, null, null, null, null, null, null, null, null];
displayController();
turnCounter = 1;
});
I have tried changing the location of the reset function but that didn’t work, adding a variable that the button changes to false to bypass checking if the game is over in some parts and that didn’t do anything, and as I’ve been going at this for around an hour, I’ve tried a couple other things I can’t think of off the top of my head. Thanks for your help!
I am using the svg widget below from this answered question
Capture Signature using HTML5 and iPad
to create a capturable signature. The code as is works but when I put content above it such as text in a <p> tag it’s stops working, which is problematic as I need it at the bottom of a document. Does anyone know why it stops working and how to make it work no matter where it is positioned in the html page?
//init
let r = document.getElementById('r'),
p = document.getElementById('p'),
signaturePath = '',
isDown = false,
svg = document.getElementById('sig_panel'),
b_show = document.getElementById('show'),
b_clear = document.getElementById('clear'),
pathdata = document.getElementById('pathdata');
//drawing functions
function isTouchEvent(e) {
return e.type.match(/^touch/);
}
function getCoords(e) {
if (isTouchEvent(e)) {
return e.targetTouches[0].clientX + ',' + e.targetTouches[0].clientY;
}
return e.clientX + ',' + e.clientY;
}
function down(e) {
signaturePath += 'M' + getCoords(e) + ' ';
p.setAttribute('d', signaturePath);
isDown = true;
if (isTouchEvent(e)) e.preventDefault();
}
function move(e) {
if (isDown) {
signaturePath += 'L' + getCoords(e) + ' ';
p.setAttribute('d', signaturePath);
}
if (isTouchEvent(e)) e.preventDefault();
}
function up(e) {
isDown = false;
if (isTouchEvent(e)) e.preventDefault();
}
//input handlers
r.addEventListener('touchstart', down, false);
r.addEventListener('touchmove', move, false);
r.addEventListener('touchend', up, false);
r.addEventListener('mousedown', down, false);
r.addEventListener('mousemove', move, false);
r.addEventListener('mouseup', up, false);
r.addEventListener('mouseout', up, false);
//helper functions
function clearSignature() {
pathdata.textContent = '';
signaturePath = '';
p.setAttribute('d', '');
}
function getSignature() {
pathdata.textContent = signaturePath;
return signaturePath;
}
//button handlers
b_show.addEventListener('click', getSignature);
b_clear.addEventListener('click', clearSignature);
svg {
margin: .5em;
border: 1px solid gray;
border-radius: .5em;
}
.flex {
display: flex;
}
button {
margin: .5em;
}
#pathdata {
font-family: monospace;
background: #ddd;
padding: 1em;
margin: 1em .5em;
}
<svg id="sig_panel" xmlns="http://www.w3.org/2000/svg" width="300" height="100" viewBox="0 0 300 100">
<rect id="r" width="300" height="100" fill="#ffa"/>
<line x1="0" y1="80" x2="300" y2="80" stroke="#666" stroke-width="1" stroke-dasharray="3" shape-rendering="crispEdges" pointer-events="none"/>
<path id="p" stroke="navy" stroke-width="2" fill="none" pointer-events="none"/>
</svg>
<div class="flex">
<button id="show">Show signaure path data</button>
<button id="clear">Clear signature</button>
</div>
<div id="pathdata"></div>
Today it started sending this message, idk why. The code is from my apps scripts.
function codigo2() {
var url = 'https://rest.coinapi.io/v1/exchangerate/BTC/USD';
var hoja = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Hoja 2');
var apiKey = '';
var options = {
headers: {
"X-CoinAPI-Key": apiKey
}
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
hoja.appendRow([data.rate]);
}
And the response error:
Exception: Request failed for https://rest.coinapi.io returned code 550. Truncated server response: {
"error": "You requested specific single item that we donu0027t have at this moment."
} (use muteHttpExceptions option to examine full response)
codigo2 @ A Recolector.gs:11
I try to search for doc but my code level in this type of things is to low, and chat didnt give me that much help.
I’m trying to build a Chrome extension that injects a Lit-based component into the DOM of any website. This component should appear as an overlay on top of the existing page content.
I’ve tried creating a Lit component and injecting it into the document body, but the component doesn’t render.
I’m looking for guidance on:
Best practices for creating overlay components with Lit.
Any specific considerations for using Lit in a Chrome extension environment.
Any code examples or suggestions would be greatly.
The goal is to be able to click a button on a WIX-page with a URL.
The Site looks like this for example:
Button1 shows container1 and Button2 toggles to container2
The code for this would be:
$w.onReady(function() {
const buttons2 = [$w('#b1'), $w('#b2')];
const boxes2 = [$w('#G1'), $w('#G1e')];
buttons2.forEach((button, index) => {
button.onClick(() => {
showBox(index, boxes2);
});
});
});
function showBox(index, boxes) {
boxes.forEach((box, boxIndex) => {
if (boxIndex === index) {
box.expand();
} else {
box.collapse();
}
});
}
Now this should be achieved by adding to the same URL a trigger:
I tried it this way:
function getUrlParameter(name) {
const results = new RegExp('[?&]' + name + '=([^&#]*)').exec(wixLocation.url);
return results === null ? null : decodeURIComponent(results[1].replace(/+/g, ' '));
}
$w.onReady(function() {
if (getUrlParameter('trigger') === 'click') {
$w('#b2').click();
}
});
…but it did not work because in WIX the property ‘click’ does not exist on type ‘Button’.
Does someone know how to achieve this or is this even doable on WIX.com?
I’m build a mini sendgrid alternative. I want to use Amazon SES to add multiple domains to my account so that my clients can send their emails from their domains. What are the steps (via API) to be able to add these multiple domains to my SES account so that I can enable my clients to send their emails? I’m guessing I will have to validate these domains first. Is there an API to do that? And then what else?
I am trying to familiarize myself with a new-to-me library called Absurd-SQL.js.
https://www.npmjs.com/package/absurd-sql
The point of this library is to create an in memory sqlite db using webassembly, use it for queries, but also store its data in the browser IndexedDB for persistent storage.
I am able to create an in-memory SQLite database, and execute queries on it. I can see that it stores persistent data in the browser IndexedDB as an array buffer.
When the page is refreshed, the in-memory sqlite db is gone, as expected, and needs to be recreated.
The problem I’m having is that I don’t know how to get the data from the IndexedDB… is there a function call to do this from the Absurd-SQL library? I could not find anything in the documentation or examples unless I’ve missed something.
I want the in-memory sqlite db to be recreated from the data stored in the IndexedDB on page reload, but there does not seem to be any way to retrieve the data from the IDB using Absurd-SQL. It may be something simple I’ve just missed, would appreciate any feedback on this.
Hi all i’m trying to figure out a way to assign a uniqe identifier to each row but keep the ids uniqe identifer the same as each row. Still learning javascript..
for first row:
id=row1, id=addbtn1, id=comment1
for second row:
id=row2, id=addbtn2, id=comment2, id=formAttachment2
for third row:
id=row3, id=addbtn3, id=comment3, id=formAttachment3
<div class="row" id="row" name="row">
<div class="col-auto" id="col">
<div id="AddButton">
<br /><button name="addbtn" type="button" class="btn btn-link addbtn" style="font-size: 11px; margin-top: -40px" id="addbtn"><font color="green"><b>+ Add</b></font></button>
</div>
</div>
<div class="col-auto" id="col">
<textarea class="form-control" rows="1" id="comment" cols="75" name="comment"></textarea>
</div>
</div>
<div class="row" id="row" name="row">
<div class="col-auto" id="col">
<div id="AddButton">
<br /><button name="addbtn" type="button" class="btn btn-link addbtn" style="font-size: 11px; margin-top: -40px" id="addbtn"><font color="green"><b>+ Add</b></font></button>
</div>
</div>
<div class="col-auto" id="col">
<textarea class="form-control" rows="1" id="comment" cols="75" name="comment"></textarea>
</div>
<div class="col-auto" id="col">
<form method="post" enctype="multipart/form-data">
<div class="mb-4">
<div class="row">
<div class="col-auto">
<input type="file" name="file" class="form-control" id="formAttachment" style="width: 500px" />
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row" id="row" name="row">
<div class="col-auto" id="col">
<div id="AddButton">
<br /><button name="addbtn" type="button" class="btn btn-link addbtn" style="font-size: 11px; margin-top: -40px" id="addbtn"><font color="green"><b>+ Add</b></font></button>
</div>
</div>
<div class="col-auto" id="col">
<textarea class="form-control" rows="1" id="comment" cols="75" name="comment"></textarea>
</div>
<div class="col-auto" id="col">
<form method="post" enctype="multipart/form-data">
<div class="mb-4">
<div class="row">
<div class="col-auto">
<input type="file" name="file" class="form-control" id="formAttachment" style="width: 500px" />
</div>
</div>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function () {
var addrow = 0;
$("[name='row']").each(function () {
addrow = addrow + 1;
$(this).attr("id", "row" + addrow);
});
});
</script>
i tried manipulating the script each function but have not had any luck yet.
For some reason this component is giving me infinite reloads when one function is called:
I have put the locations in bold comments where the errors might be occurring.
import React, { useState, useRef, useContext, useEffect } from 'react';
import { useQuery } from 'react-query';
import { Loading } from '../Elements/LoadingComponent';
import { Row, Col } from 'react-bootstrap';
import AddDesks from '../Elements/Layout/AddDesks';
import Status from '../Elements/Layout/Status';
import { Desk } from '../Elements/Layout/Desks';
import { SiteMapContext } from '../../App';
import {
Layout_Get_Sites,
Layout_Get_Desk_Types,
Layout_Undo_Change,
Layout_Redo_Change,
Layout_Clear_Desk,
Layout_Delete_Desk,
Layout_Update_Desklist,
Layout_Restore_All,
Layout_Update_Desk_Data,
Layout_Create_Desk,
Layout_Set_UserImage,
Layout_Update_Desk_Sizes
} from '../../network/Layout_Creator';
import '../../shared/styles/layout.css';
const LayoutMap = (props) => {
//const dispatch = useDispatch();
const mapRef = useRef();
const mapContainer = useRef();
const siteMap = useContext(SiteMapContext);
let roles = siteMap.siteMapData.user.roles;
const isAdmin = roles.indexOf('admin') + roles.indexOf('system') > 0
let siteCount = 0;
let mapsLoaded = false;
let mapScale = 0;
let currentMap = -1;
const [desks, setDesks] = useState({ past: [], present: [], future: [] });
const [currentDesk, setDesk] = useState(-1);
const [deskTypes, setDeskTypes] = useState(-1);
const [maps, setMaps] = useState({ maps: [] });
const [editMode, setEditMode] = useState(false);
const [deskComponents, setDeskComponents] = useState(null);
const { isLoading: areMapsLoading, refetch } = useQuery('LayoutMaps', () => Layout_Get_Sites(siteCount),
{
staleTime: Infinity,
refetchInterval: false,
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
onSuccess: (data) => {
let map = data.maps;
if (map) {
let newMaps = [...maps.maps, map];
setMaps({ maps: newMaps })
siteCount = newMaps.length;
mapsLoaded = data.done;
}
if (!data.done) refetch();
},
})
useEffect(() => {
const loadDeskTypes = async () => {
let dt = await Layout_Get_Desk_Types();
setDeskTypes(dt);
}
loadDeskTypes();
}, [])
//called when location Select is used
const changeMap = target => {
console.log("Layout.changeMap");
setDesk(null);
const site = parseInt(target.value);
//layout_Set_Current_Site(site);
currentMap = site;
setEditMode(false);
//THIS IS WHERE THE INFINITE RELOAD LOOP STARTS
const desks = buildDesks();
setDeskComponents(desks);
}
const getScale = () => {
const site = maps.maps[currentMap] //the id on the select
if (!site) return;
let newMap = document.getElementById("floorMap");
let map = mapRef.current;
let mapWidth = map?.getBoundingClientRect()?.width;
let newMapWidth = newMap?.getBoundingClientRect()?.width;
let scale = (mapWidth && site?.wMM) ? (mapWidth / site.wMM) : 1;
mapScale = scale;
return scale;
}
const clickMap = () => {
setDesk(null);
}
const createDesk = async (newDesk) => {
//TODO: Modify to update data before database update
Layout_Create_Desk(newDesk)
.then(data => {
let newDesks = data.desks;
setDesks({ past: desks.present, present: newDesks, future: [] });
});
}
const updateDesk = (desk) => {
//TODO write fn to update the data for a desk and update database
}
const setUserImage = (file) => {
Layout_Set_UserImage(file, currentDesk)
}
const AddDesksFns = {
Update_Desklist: setDesks,
Create_Desk: createDesk
}
const StatusFns = {
Update_Desklist: setDesks,
Update_Desk_Data: updateDesk,
Set_UserImage: setUserImage,
Set_Current: setDesk
}
const buildMapOption = (site, index) => {
var ret = <option value={index} key={site.id}>{site.SiteName}</option>
return ret;
}
const buildMapSelector = () => {
var ret =
<select onChange={(e) => changeMap(e.target)} value={maps.current ?? -1}>
<option id='-1'>Select Site...</option>
{
maps.maps.map((site, index) => buildMapOption(site, index))
}
</select>
return ret;
}
//THIS IS AN EXTERNAL COMPONENT WHICH MAY BE RESPONSIBLE FOR INFINITE RELOADS
const buildDesk = (desk, scale) => {
const res = <Desk key={desk.id} desk={desk} scale={scale} deskTypes={deskTypes} currentDesk={currentDesk} fns={StatusFns} />
return res;
}
const buildDesks = () => {
try {
let scale = getScale();
let res = maps.maps[currentMap]?.desks.map(desk => buildDesk(desk, scale));
//RES IS AN ARRAY OF 61 DESK COMPONENTS
return res
} catch (error) {
console.error('Error building desks:', error);
return null;
}
};
return (
<div>
<Row>
<Col sm={1}>
{(isAdmin && !areMapsLoading) ?
<span style={{ 'whiteSpace': 'nowrap', 'backgroundColor': '#ccc' }}>
<label htmlFor='layoutEditSelect'>Edit</label>
<input id='layoutEditSelect' type='checkbox'
onClick={async (e) => { setEditMode(e.target.checked); }}
/>
</span>
: <span></span>
}
</Col>
<Col sm={10}>
{(editMode && currentDesk != null) ?
<div style={{ position: 'absolute', top: '100px', left: '300px' }}>
<Row>
<Col>Left</Col><Col>{Math.round(currentDesk.x)}</Col>
<Col>Height</Col><Col>{currentDesk.height}</Col>
</Row>
<Row>
<Col>Top</Col><Col>{Math.round(currentDesk.y)}</Col>
<Col>Width</Col><Col>{currentDesk.width}</Col>
</Row>
<Row>
<Col>Rotation</Col>
<Col>{currentDesk.rotation}°</Col>
</Row>
</div>
: ''
}
</Col>
</Row>
<Row>
<Col sm={1}>
<Row>
<Col>
{!areMapsLoading ?
buildMapSelector()
:
<Loading title="Map Data" />
}
</Col>
<Col>
<AddDesks
maps={maps}
deskTypes={deskTypes}
editMode={editMode}
scale={mapScale}
fns={AddDesksFns}
/>
</Col>
</Row>
</Col>
<Col sm={10} id="Layout_Map_Container" ref={mapContainer} >
{/* <BuildMap map={maps.maps[props.maps.current]} fns={props.MapFunctions} scale={props.scale} /> */}
{/*onClick={clickDesk}*/}
<div ref={mapContainer}
style={{ width: '100%', height: `${window.height}px`, position: 'relative' }}
onClick={()=>clickMap()}
onLoad={() => { getScale(); clickMap(); } /*If map is reset, set current desk to null*/}
className='map'
id="Layout_SiteMap_Img"
>
<img src={`data:image/jpeg;base64,${maps.maps[currentMap]?.SiteBackground ?? 'R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='}`}
style={{ width: '100%', position: 'absolute' }}
alt={`Layout plan for ${maps.maps[currentMap]?.currentSite?.SiteName}`}
ref={mapRef}
id="floorMap"
/>
<React.Fragment id="desks">
{deskComponents}
</React.Fragment>
</div>
</Col>
</Row >
<Status desk={currentDesk} currentDesk={currentDesk} moveData={desks} />
</div>
)
}
export default LayoutMap;
I have been troubleshooting this for long enough that it is getting irritating.
I will provide CSV of desks and desktypes but they contain large strings for the images so prefer not to if possible.
I am getting a Jest encountered an unexpected token. I tried a numerous of configuration but was unable to get it to work.
tsconfig.json
{
"extends": "@tsconfig/node18",
"compilerOptions": {
"outDir": "./dist/lib",
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true
},
"exclude": ["cdk.out", "build", "node_modules", "dist"]
}
jest.config.js
module.exports = {
testMatch: ['**/*.test.js'],
preset: 'ts-jest',
testEnvironment: 'node',
};
babel.config.js
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
};
I tried a numerous of different jest.config.js but had no luck
When I do this config, the parsing seems to work but I get a ReferenceError: BWTC is not defined in another test file.
module.exports = {
testMatch: ['**/*.test.js'],
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\.(ts|tsx)?$': 'ts-jest',
'^.+\.(js|jsx)$': 'babel-jest',
},
transformIgnorePatterns: [],
};
Here are other configs I attempted but failed
module.exports = {
testMatch: ['**/*.test.js'],
preset: 'ts-jest',
testEnvironment: 'node',
transformIgnorePatterns: ['node_modules/(?!(.*\.mjs$|pdfjs-dist))'],
};
module.exports = {
testMatch: ['**/*.test.js'],
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\.(js|ts|tsx)$': 'ts-jest',
},
};
Original error:
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
I can’t figure out the correct way to pass a system prompt to claude 3 haiku through AWS Bedrock InvokeModelWithResponseStreamCommand. When I try to add { role: “system”, content: systemPrompt } to the messages array it breaks. I’ve scoured Anthropic’s and AWS Bedrock’s documentation but can’t find out whether system prompts are suppposed to be in a separate field from messages. According to anthropic docs it should be, but it does not appear that AWS Bedrock supports a separate system prompt field outside of messages in its JS SDK.
import { NextResponse } from "next/server";
import { BedrockRuntimeClient, InvokeModelWithResponseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
const systemPrompt = "todo"
export async function POST(req) {
// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });
const data = await req.json();
// Set the model ID, e.g., Claude 3 Haiku.
const modelId = "anthropic.claude-3-haiku-20240307-v1:0";
console.log(data)
const payload = {
anthropic_version: "bedrock-2023-05-31",
max_tokens: 10000,
messages: [
{"role": "user", "content": "Hello there."},
{"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
{"role": "user", "content": "Can you explain LLMs in plain English?"},
],
}
// Create a command with the model ID, the message, and a basic configuration.
const command = new InvokeModelWithResponseStreamCommand({
contentType: "application/json",
body: JSON.stringify(payload),
modelId,
});
const stream = new ReadableStream({
async start(controller) {
try {
// Send the command to the model and wait for the response
const response = await client.send(command);
let completeMessage = "";
// Extract and print the streamed response text in real-time.
for await (const item of response.body) {
const chunk = JSON.parse(new TextDecoder().decode(item.chunk.bytes));
const chunk_type = chunk.type;
if (chunk_type === "content_block_delta") {
const text = chunk.delta.text;
completeMessage = completeMessage + text;
controller.enqueue(text);
process.stdout.write(text);
}
}
} catch (err) {
controller.error(err)
} finally {
controller.close()
}
}
})
return new NextResponse(stream);
}
The error when I try to add the system prompt to the messages array:
Error: failed to pipe response
...
[cause]: ValidationException: Malformed input request: #: subject must not be valid against schema {"required":["messages"]}#/messages/0/role: system is not a valid enum value, please reformat your input and try again.
at de_ValidationExceptionRes (webpack-internal:///(rsc)/./node_modules/@aws-sdk/client-bedrock-runtime/dist-es/protocols/Aws_restJson1.js:379:23)
at de_CommandError (webpack-internal:///(rsc)/./node_modules/@aws-sdk/client-bedrock-runtime/dist-es/protocols/Aws_restJson1.js:212:25)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async eval (webpack-internal:///(rsc)/./node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js:8:24)
at async eval (webpack-internal:///(rsc)/./node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js:25:20)
at async eval (webpack-internal:///(rsc)/./node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js:41:46)
at async eval (webpack-internal:///(rsc)/./node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js:9:26)
at async Object.start (webpack-internal:///(rsc)/./app/api/chat/route.js:118:34) {
'$fault': 'client',
'$metadata': {
httpStatusCode: 400,
requestId: '5c49e0b0-d781-4c5a-bd7d-0823a50a763f',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
}
}
}
POST /api/chat 500 in 928ms
I’ve tried to add { role: “system”, content: systemPrompt } as an additional message in the messages array and as a separate (“system”) field. Using the external system field approach appears to be the correct way according to Anthropic’s docs, but AWS Bedrock doesn’t appear to support an external system field in its InvokeModelWithResponseStreamCommand Bedrock Runtime API. I’m expecting a streaming response that takes in user prompts and responds within the constraints of the system prompt.
https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html
https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/system-prompts
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_bedrock-runtime_code_examples.html#anthropic_claude