What are the ways to protect environment configuration files in Angular/React during build?
I am using Angular: environment.ts and environment.prod.ts. Does this protect it, and what other ways are there?
please help me. Thank you
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
What are the ways to protect environment configuration files in Angular/React during build?
I am using Angular: environment.ts and environment.prod.ts. Does this protect it, and what other ways are there?
please help me. Thank you
When defining functions in TypeScript, is the following approach — defining event types in a separate types.ts file and then declaring functions as const with that type — considered a recommended practice in modern development?
types.ts:
export type MouseEventHandler = EventHandler<MouseEvent>;
event-listeners.ts:
export const onClickCreateItem: MouseEventHandler = async (event, deps) => {
// some logic
};
event-listeners.ts:
export async function onClickCreateItem(
event: MouseEvent,
deps: CreateItemDependencies
) {
// some logic
}
Thanks in advance!
MERCURIOUS CONFRATERNITY
Mercurious occult Member +2347063372861
WELCOME TO THE WORLD OF BILLIONAIRE MERCURIOUS CONFRATERNITY OCCULT SOCIETY WHERE TO ACHIEVE ALL YOUR DESIRE IN LIFE, JOIN US NOW AND BE FREE FROM POVERTY AND PAINS, WE ARE HERE TO CHANGE YOU FROM BAD TO GOOD ONCE YOU HAVE THE MIND TO DO WHAT IT TAKE TO MAKE WEALTH AND FORTUNES CALL +2347063372861 NOW! Do you want to be a member of MERCURIOUS OCCULT as a brotherhood that will make you rich and famous in the world and have power to control people in the high place in the worldwide .Are you a pastor, business man or woman, artist, politician, musician, student, do you want to be rich, famous, powerful in life, join the Mercurious fraternity cult today and get instant rich sum of 250 million naira in a month, and a free home.
BENEFITS GIVEN TO NEW MEMBERS WHO JOIN MERCURIOUS
A Cash Reward of USD $800,000 USD
A New Sleek Dream CAR valued at USD $500,000 USD
3.A Dream House bought in the country of your own choice
One Month holiday (fully paid) to your dream tourist destination.
One year Golf Membership package
A V.I.P treatment in all Airports in the World
A total Lifestyle change
Access to Bohemian Grove
Monthly payment of $1,000,000 USD into your bank account every month as a member
One Month booked Appointment with Top 5 world Leaders and Top 5 Celebrities in the World.
If you are interested of joining us in the great brotherhood of BILLIONAIRES MERCURIOUS Occult temple CALL NOW FOR ENQUIRIES +2347063372861
HAVE YOU YOU BEEN SEEKING FOR OPPORTUNITIES TO JOIN A SACRED BROTHERHOOD OCCULT FOR MONEY RITUAL IN NIGERIA? This is your time to make a positive change in your life, in as much as you have the bravery and courage to withstand the difficult parts of this brotherhood. +2347063372861, Every member of this Society is entitled to all the Secret knowledge of Spiritual wealth and power, money is assured, power is assured, fame is assured if you want it, protection is also assured. But have it in mind that becoming a member of this occult you’re to perform a great sacrifice to please the Lord Spiritual and all your heart desires will be granted. Call now for enquiries +234706337286 BILLIONAIRES MERCURIOUS OCCULT IS A SACRED FRATERNITY WITH A GRAND LODGE TEMPLE SITUATED IN ENUGU STATE NIGERIA, OUR NUMBER ONE OBLIGATION IS TO MAKE EVERY INITIATE MEMBER HERE RICH AND FAMOUS IN OTHER RISE THE POWERS OF GUARDIANS OF AGE+. +2347063372861..
When defining functions in TypeScript, is the following approach — defining event types in a separate types.ts file and then declaring functions as const with that type — considered a recommended practice in modern development?
types.ts:
export type MouseEventHandler = EventHandler<MouseEvent>;
event-listeners.ts:
export const onClickCreateItem: MouseEventHandler = async (event, deps) => {
// some logic
};
event-listeners.ts:
export async function onClickCreateItem(
event: MouseEvent,
deps: CreateItemDependencies
) {
// some logic
}
Thanks in advance!
The closedby attribute is supported in all major browsers except Safari. For those browsers, setting closedby="all" on a dialog element enables light dismiss, including clicking on dialog::backdrop.
I tried to implement feature detection for Safari as follows (this is inside a click event listener):
// modal.close() is handled by `closedby` attribute on <dialog>
// except in Safari.
if (`closedby` in navigator) {
console.log(`closedby supported`);
} else {
modal?.close();
console.log(`closedby not supported`);
};
But even on supporting browsers, the console message is closedby not supported.
How can I detect support for closedby?
Note: modal is a variable holding the dialog element.
cart → reserved (or pending) → payment_in_progress → paid → fulfilled
Failures / alternatives: reserved → expired → cancelled (stock returned); payment_in_progress → failed → cancelled (release stock or keep for manual review); paid → refunded (store refund events).
Make allowed transitions explicit in code to prevent invalid state changes.
Use the above pages while implementing each corresponding module
Read before coding: Express guide (routing & middleware).
Algorithm (no code):
Create Express app and structured router directories: /routes, /controllers, /models, /services, /utils.
Add JSON body parser, CORS (restrict origins in prod), Helmet for headers, rate limiter for sensitive endpoints, error handler middleware.
Load .env and validate presence of required keys (MONGO_URI, PAYPAL_CLIENT_ID, PAYPAL_SECRET, WEBHOOK_ID).
Where to read:
Algorithm:
findOneAndUpdate + compensating rollback.Read:
Design checklist (fields):
products: _id, name, description, category, price, currency, stock, imageUrl, createdAt, updatedAt
name + description for search.category, price, stock (for low stock queries).orders: _id, orderNumber, items[{productId, qty, priceAtPurchase}], totalAmount, currency, customer{}, status, paypal:{orderId,captureId,raw}, createdAt, expiresAt, paymentEvents[]counters or use a sequence generator for orderNumber.Read:
Algorithm:
GET /products:
q, category filters, price range, sort, page, limit.$text search if q present; project score. Apply filters; send pagination meta. (If you need better search later, use Atlas Search.)GET /products/:id: validate id, return product details.Read:
POST /orders — create + reserve stock (core corrected algorithm)This is critical — follow exactly.
Algorithm:
price for each product and summing price * qty. Store priceAtPurchase per item. (This prevents price manipulation.)findOneAndUpdate({_id: productId, stock >= qty}, {$inc: {stock: -qty}}). If any update fails (not enough stock), abort transaction and return which items are out of stock.order document with status = "reserved", expiresAt = now + RESERVATION_TTL (e.g., 15 minutes). Store orderNumber (get next from counters via atomic $inc).orderId + expiresAt.For each item findOneAndUpdate with stock >= qty. Track successful updates. If any fail, do compensating increments for previously decremented products (careful to log failures and retry). Create order only after all decrements succeed. (This is less safe than transactions but workable.)
Why this corrected approach:
POST /paypal/create-order (server create PayPal order)Algorithm:
orderId. Server re-fetches order and recomputes/validates amounts.paypal.orderId in orders.paypal.orderId and update order status = "payment_in_progress". Return paypal.orderId to client. (Do not let client create PayPal order with client-side totals.)Algorithm (server capture endpoint):
POST /paypal/capture with orderId (internal) & paypalOrderId.capture endpoint server-side, verifies:
order.totalAmount and currency matches,orders.status = "paid", store captureId and raw response in orders.paypal.payment_in_progress and queue retry; DO NOT mark paid unless verified.Webhook redundancy:
POST /webhooks/paypal to accept PayPal events (e.g., PAYMENT.CAPTURE.COMPLETED) and verify each webhook using PayPal signature verification or verify endpoint. Use idempotent processing (store PayPal event id).Read:
Algorithm:
verify-webhook-signature or equivalent; reject if verification fails.order by paypal.orderId or by captureId in payload. Re-verify amounts if necessary via server call to PayPal.orders.status accordingly (e.g., paid), store raw event, and ack.Algorithm (no code):
orders where status = "reserved" and expiresAt < now.products.stock by each reserved qty (reverse the decrements) and update orders.status = "expired" / cancelled. Store a release event in order.paymentEvents.Why: TTL deletes will not restore stock; TTL is for deletion only — so we implement this worker to release reserved stock reliably.
Read before coding: Redux Toolkit usage & React fundamentals.
Logical slices:
productsSlice — search results, product details, loading/errors.cartSlice — cart items, computed totals, persist to localStorage (rehydrate on load).orderSlice — create order (reservation), track orderId, expiresAt, order status.uiSlice — global toasts / loaders.Algorithm for checkout UI flow:
POST /orders (server will compute totals and reserve stock). If server returns stock error, update cart & show item specific messages.POST /paypal/create-order to get paypal.orderId (server side), then place PayPal button on page using PayPal JS SDK with createOrder returning server order id (or pass paypalOrderId to SDK). On approval, call server POST /paypal/capture.order/:orderNumber status page with polling or server push to show paid once webhook processed.Read:
expiresAt) so user knows time left.localStorage and allow merging with server cart if user logs in (optional).Algorithm (analytics endpoint):
orders.status = "paid", date range filter.$unwind items, $group by items.category (or product ref) summing qty and revenue = qty * priceAtPurchase.$sort by revenue/qty, $limit. Use $project to shape results. (This is standard aggregation pipeline use.)Read:
POST /orders, /paypal/*, login).paid.products endpoints + seed DB + text index.POST /orders with transactional reserve algorithm (or safe fallback).POST /paypal/create-order (server), integrate PayPal Orders API.POST /paypal/capture server capture + POST /webhooks/paypal with signature verification + idempotency.Initialize Project
npm init -y, install: express, mongoose, cors, dotenv, express-validator, paypal-rest-sdk (or official PayPal SDK).
Setup folder structure:
/backend
/models
/routes
/controllers
/config
Configure MongoDB
mongoose.connect(process.env.MONGO_URI).Create Models
Core APIs
/api/products → list, filter, search (with regex or $text index)./api/products/:id → single product./api/orders → create order (validations)./api/orders/:id → get order details./api/paypal/create-order → initiate PayPal order./api/paypal/capture-order → confirm payment + update order status./api/analytics → MongoDB aggregation (sales by category, top sellers, low stock).Middleware
express-validator).npx create-react-app frontendreact-router-dom, @reduxjs/toolkit, react-redux, axios.Store structure:
/frontend/src
/store
store.js
productSlice.js
cartSlice.js
orderSlice.js
Slices:
productSlice → fetch, search, filter.cartSlice → add/remove/update items, persist in localStorage.orderSlice → create order, track status.Header → nav + cart icon.ProductList → grid of product cards.ProductCard → image, name, price, add-to-cart.Cart → items, quantity control, summary.Checkout → form for customer info, order summary.PayPalButton → integrate SDK.OrderConfirmation → display after payment.Correct Flow:
/api/products)./api/orders)./api/paypal/create-order → PayPal popup opens./api/paypal/capture-order.I upgraded an app to NextJS v15 and my dynamic routes are broken after npm run build with output: "export".
When I refresh the browser on a dynamic route like /projects/123, the root page renders instead of my [id].js component. The URL stays correct but the wrong page loads.
output: "export" in next.config.jspages/projects/[id].js/projects/123 via Link – ✅ works fine/projects/123)Had to add this to _app.js to force the router to recognize the route:
useEffect(() => {
const path = window.location.pathname;
if (path !== '/' && router.pathname === '/') {
router.replace(path);
}
}, []);
Unfortunately, the above hack breaks 404 routing because every route is considered valid. It’s odd to me that this worked fine in Next v13, but now I can’t find documentation that it was actually ever supported.
I have 2 very simular PHP scripts on the same server. The HTML part of this scripts are totally the same. Only the PHP subroutines are quite different.
Both scripts running in parallel in the same browser window, One is executing in the normal quick way. The other is suddenly very slow it takes up to 60 seconds.
I use microtime to messure the executing time and find out that whole execution time of the php script is only around 0.1 second.
But the big diffrence of the whole display time is on PC, Notebook and Smartphone always the same.
I have no idea what the reason could be.
Here the HTML part of my scripts.
<!DOCTYPE html>
<html lang="de">
<head>
<title>CurrentListeners</title>
<meta http-equiv="content-type" content="text/html" /> <meta charset="UTF-8" />
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="Expires" content="0" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="showListeners.css">
</head>
<body>
<?php echo getHTML(); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script type="text/javascript" src="showListeners.js"></script>
</body>
</html>
`
It’s just being weird:
https://editor.p5js.org/Argumentative/sketches/dJydzUbU_
I’ve followed multiple papers on the subject but it’s taken quite a bit of logic on my part to get something relatively similar to perlin noise. I get the feeling I’ve just matched up the corners to the equation incorrectly. The paper I’m basing this all off of is from the University of Maryland:
https://www.cs.umd.edu/class/spring2018/cmsc425/Lects/lect13-2d-perlin.pdf
NOTE:
I have no interest in anything other than 2D perlin noise.
I want to develop a real-time audio translator extension as instance for chrome and using a local translation service. The services provides an API to pass an audio snippet in .wav or .mp3 format and returns the translation as string. For example, to translate a youtube video, the audio has to pass to the API and the returned text should be shown in the video as subtile.
API service
Input:
How to I implement a browser plugin that sends audio chunks (3 or 5 seconds long) to the API service and show the returned translated text as subtitle in real time to show the video?
The main challenge is to capture the audio, chunk it and send to the API. I tried to use MediaRecoder but faces a lot errors and I don’t if this the right approach.
A good minimal example would help a lot.
I’m developing a simple web app using HTML and vanilla JavaScript. The app allows users to upload an image, which is then sent to Firebase Storage. My web app is hosted at https://esstsas.net.
The Problem:
When I try to upload an image to my Firebase Storage bucket (gs://checksst-faster.firebasestorage.app), the request fails with a CORS preflight error in the browser console:
Access to XMLHttpRequest at ‘…’ from origin ‘https://esstsas.net‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
This is the relevant JavaScript code that handles the image upload: I am using the Firebase JS SDK (v11.6.1). The storage object has been correctly initialized.
JavaScript
// This function is called when the "Save" button is clicked
async function saveInspection() {
const file = lastSelectedFile; // lastSelectedFile is the user's selected image File object
const userId = auth.currentUser.uid;
if (!file || !userId) {
console.error("File or User ID is missing.");
return;
}
try {
console.log("Step 1: Resizing image...");
const resizedImageBlob = await resizeImage(file); // Resizes image to a Blob
console.log("Step 2: Uploading to Storage...");
const fileName = `${Date.now()}-${file.name}`;
const storageRef = ref(storage, `images/${userId}/${fileName}`);
// This is the line that fails
const uploadTask = await uploadBytes(storageRef, resizedImageBlob);
console.log("Step 3: Getting download URL...");
const downloadURL = await getDownloadURL(uploadTask.ref);
// ... code to save the downloadURL to Firestore would go here
console.log("Upload successful:", downloadURL);
} catch (error) {
console.error("DETAILED UPLOAD ERROR:", error);
}
}
What I’ve already tried (Troubleshooting Steps):
I am certain this is not a simple configuration error because I have performed extensive troubleshooting:
CORS Configuration: I used the gcloud CLI to set the CORS policy on my bucket. The command gsutil cors get gs://checksst-faster.firebasestorage.app confirms the policy is set correctly with my origin: [{"origin": ["https://esstsas.net", "https://www.esstsas.net"], "method": ["GET", "POST", "OPTIONS"], ...}]
Wildcard Test: As a test, I also applied a wildcard policy with "origin": ["*"]. The error still persisted.
Client-Side Caching: I have ruled out browser caching by performing a hard refresh (Ctrl+Shift+R), testing in incognito mode, using a completely different browser, and testing on a different network (mobile hotspot).
Firebase Rules: My Firestore and Storage security rules are correctly configured to allow access for authenticated users (allow read, write: if request.auth != null && request.auth.uid == userId;).
Even with the server-side CORS configuration confirmed as correct and after eliminating all client-side caching possibilities, the browser still receives a failed preflight response. I cannot create a formal Google Cloud support ticket as I am on the free plan.
Is there any other project-level setting, network issue, or known bug that could be overriding the bucket’s CORS policy?
How can I reliably detect the end of the page in Safari on macOS 15 using plain JavaScript, in a way that works across zoom levels and dynamic content?
I have the following code that scrolls the page downward smoothly:
window.__scrollInterval = setInterval(() => {window.scrollBy(0, 0.3, 'smooth');}, 0);
What I need is a reliable way to detect when the page has reached the bottom. The detection must work regardless of zoom level, which is where most solutions fail—especially in Safari.
When the end of the page is reached, I want to trigger:
alert('End');
Requirements:
Must work in Safari on macOS 15
Must be written in plain JavaScript (no libraries)
Must be robust against zoom level changes
Pages to test on:
Legacy websites from 1999–2007 (static HTML, minimal JS)
I am working on a react front-end project want to add a loading icon for data loading time. It worked well at the initial time, but did not work if the data changed, here is the useEffect to handle this:
useEffect(() => {
setLoading(true);
if (!frameResults.length) {
return;
}
if (typeof graphSetting?.movementDomain[1] === 'string') {
if (graphSetting.movementDomain[1] === 'dataMax+5') {
yAxisDomainRef.current = [0, getDataMax(frameResults) + 5];
}
} else if (typeof graphSetting?.movementDomain[1] === 'number') {
yAxisDomainRef.current = graphSetting.movementDomain;
}
}, [frameResults]);
useEffect(() => {
setLoading(true);
if (frameResults.length < 1) {
return;
}
Boolean(selectedIdx)
const options = new Array({ value: 0, label: t("Overview") })
.concat(frameSectionStartTime.map(
(time, idx) => ({
value: idx + 1,
label: `${t("Section")} ${idx + 1}: ${time.split(" ")[1]}`
})
));
setSectionOption(options);
setSelected(1);
setLoading(false);
}, [frameResults]);
useEffect(() => {
setLoading(true);
if (frameResults.length < 1) {
return;
} else if (selectedIdx == 0) {
const sectionStart = new Date(frameSectionStartTime[0]);
const lastframe = frameResults[frameResults.length - 1].length - 1;
const lastStamp =
frameResults[frameResults.length - 1][lastframe].timestamp;
const sectionEnd = new Date(`${date} ${lastStamp}`);
setMinimapDomain({
x: [sectionStart, sectionEnd],
y: yAxisDomainRef.current
});
setZoomDomain({
x: [sectionStart, sectionEnd],
y: yAxisDomainRef.current
});
setLoading(true);
} else {
const domainStart = new Date(frameSectionStartTime[selectedIdx - 1]);
const lastframe = frameResults[selectedIdx - 1].length - 1;
const lastStamp = frameResults[selectedIdx - 1][lastframe].timestamp;
const sectionEnd = new Date(`${date} ${lastStamp}`);
const sectionLength = sectionEnd - domainStart;
const domainLength = 15000;
const domainEnd = new Date();
domainEnd.setTime(domainStart.getTime() + domainLength);
setMinimapDomain({
x: [domainStart, sectionLength >= 15000 ? sectionEnd : domainEnd],
y: yAxisDomainRef.current
});
setZoomDomain({
x: [domainStart, domainEnd],
y: yAxisDomainRef.current
});
setLoading(false);
}
}, [selectedIdx, frameResults]);
components part is like:
<Spin spinning={loading}>
<VictoryChart>...</VictoryChart>
</Spin>
I think it may due to the fact that rendering time is too quick, so the loading state cannot got back to true again. I added a timeout, it can render every time frameResult data changed, but has a slightly delay. It should render immediately once the frameResult data changed, but it now has a slightly delay and then render the loading icon.
I have a problem with vitest + coverage via V8. I want to run tests with vitest on many browsers, but i cannot even run tests because of error below
I have Vitest config like this for browser instances:
browser: {
enabled: true,
provider: 'playwright',
instances: [
{ name: 'chromium', browser: 'chromium' },
{ name: 'firefox', browser: 'firefox' }
]
},
and coverage:
coverage: {
provider: 'v8',
reporter: ['html', 'cobertura'],
reportsDirectory:'./coverage/chromium',
And when I run tests I see an error
Error: @vitest/coverage-v8 does not work with { "browser": { "provider": "playwright", "instances": [ { "browser": "chromium" }, { "browser": "firefox" } ] } } Use either: { "browser": { "provider": "playwright", "instances": [ { "browser": "chromium" } ] } } ...or change your coverage provider to: { "coverage": { "provider": "istanbul" } }
The main question is how to run test on all browsers but gather coverage only for Chromium?
I met a JS regex used for Joi validation. It is hard to understand and may I ask your help to explain it?
Joi.string().regex(/^(?=.*S).+$/).required()
It did work for validating none blank string. But don’t know how it works?