Why Svelte is converting TypeScript to JSDoc

#​638 — May 11, 2023

Read on the Web

JavaScript Weekly

The JavaScript Ecosystem is Delightfully Weird — There are plenty of examples of how JavaScript is weird but Sam focuses on the why. If you’ve been a JS developer for many years you’ll have seen it go through many phases and morph to fit its environment. Sam paints the big picture, concluding with a talk Dan Abramov gave yesterday called “React from Another Dimension.”

Sam Ruby

The New JS Features Coming in ECMAScript 2023 — The next JavaScript update brings smaller additions familiar from other languages, but there are more significant developments waiting in the wings. 

Mary Branscombe (The New Stack)

Full Stack for Front-End Engineers with Jem Young (Netflix) — Learn what it means to become a well-rounded full-stack engineer with this hands-on video course. You’ll dive into servers, work with the command line, understand networking and security, set up continuous integration and deployment, manage databases, build containers, and more.

Frontend Masters sponsor

Vue 3.3 ‘Rurouni Kenshin’ Released — Named after a popular manga series, the latest release of Vue is focused on developer experience improvements, particular for those using TypeScript.

Evan You

John Komarnicki says ▶️ Vue 3.3’s defineModel macro will change the way you write your components.

Next.js 13.4 Released — Despite the minor version bump, this is a big release for the popular React framework. The new app router and its improved approach to filesystem based routing is now offered as a stable feature, with a new concept of server actions being introduced in alpha as a way to mutate data on the server without needing to create an in-between API layer.

Tim Neutkens and Sebastian Markbåge

⚡️ IN BRIEF:

???? Svelte is converting from TypeScript to JSDoc (example).. sort of. Rich Harris popped up on Hacker News to provide some all important context but the ultimate result will be smaller package sizes and a better experience for Svelte’s maintainers.

React now has official ‘canary’ releases if you want to use newer features than in the stable releases but still be on an officially supported channel.

Newly released Firefox 113 lets you override JS files in its debugger.

No stranger to controversy, Ruby on Rails’s David Heinemeier Hansson (DHH) tweeted: ???? “TypeScript sucked out much of the joy I had writing JavaScript.”

RELEASES:

Glint 1.0 – TypeScript powered tooling for Glimmer / Ember templates.

Elementary 2.0 – JS/C++ library for building audio apps.

???? Articles & Tutorials

ES2023’s New Array Copying Methods — The newest ECMAScript spec introduces some new methods on Array that you’ll eventually find useful in your own programs. Phil gives us the tour.

Phil Nash

Private Class Fields Considered Harmful“As a library author, I’ve decided to avoid private class fields from now on and gradually refactor them out of my existing libraries.” Why? Well, that’s the interesting part..

Lea Verou

▶  I’m Done with React — Going from least-to-most important, the reasons this developer isn’t choosing React for future projects make for interesting watching, particularly if you too are overwhelmed by upheaval in the React world. Solid is one of the alternatives he has warmed to.

Adam Elmore

Constraining Language Runtimes with Deterministic Execution — Explore various challenges encountered while using different language runtimes to execute workflow code deterministically.

Temporal Technologies sponsor

Running JavaScript in Rust with Deno — Deno’s use of Rust makes it a natural choice if you’re building a Rust app and want to integrate a JavaScript engine.

Austin Poor

Regular Expressions in JavaScript — Powerful but often misunderstood, many will benefit from this roundup of the potential regexes offer to JavaScript developers.

Adebayo Adams

How to Measure Page Loading Time with the Performance API — The Performance API is a group of standards used to measure the performance of webapps supported in most modern browsers.

Silvestar Bistrović

How to Build a JS VST or Audio Unit Plugin on macOS — VSTs and Audio Units are both types of audio plugins for audio editing software and they’re usually built in C or C++. This tutorial doesn’t dig into the audio side of things, but more the practicalities of packaging things up to get started.

Chris Mendez

An Introduction to the Bun Runtime — If you’ve not yet played with the newest entrant into the JS runtime space, this is a high level overview.

Craig Buckler

2023 State of the Java Ecosystem

New Relic sponsor

Configuring ESLint, Prettier, and TypeScript Together

Josh Goldberg

DestroyRef: Your New Angular 16 Friend

Ion Prodan

Why Astro is My Favorite Framework

Ryan Trimble

???? Code & Tools

file-type 18.4: Detect the File Type of a Buffer, Uint8Array or ArrayBuffer — For example, give it the raw data from a PNG file, and it’ll tell you it’s a PNG file. Uses magic numbers so is targeted solely at non text-based formats.

Sindre Sorhus

Learn How the Rising Trend of Malicious Packages Can Affect Your Apps — Keep your applications secure with Snyk’s article on the increasing number of malicious OS packages and ways to mitigate these risks.

Snyk sponsor

Livefir: Build Reactive HTML Apps with Go and Alpine.js — Go isn’t a language that often pops up in the context of the frontend, but this is a neat integration between Go on the backend and Alpine.js up front.

Adnaan Badr

JZZ.js: A Developer Friendly MIDI library — For both browsers and Node, JZZ.js provides an abstraction over working with MIDI related concepts. There are many examples, but the easter egg in the top left is our favorite.

Sema / Jazz-Soft

htmlparser2 9.0: A ‘Fast and Forgiving’ HTML and XML Parser — Consumes documents and calls callbacks, but it can generate a DOM as well. Works in both Node and browser.

Felix Böhm

cRonstrue: Library to Convert cron Expressions into Human-Readable Form — Given something like */5 * * * *, it’ll return “Every 5 minutes”. No dependencies.

Brady Holt

Knip: Find Unused Files, Dependencies and Exports in TypeScript Projects — Being Dutch for “snip” is appropriate as Knip can trim away things that aren’t being used in your project.

Lars Kappert

jsPlumb 6.1
↳ Visual connectivity for webapps.

gridstack.js 8.1
↳ Build interactive dashboards quickly.

???? Jobs

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

Team Lead Web Development — Experienced with Node, React, and TS? Join us and lead a motivated team of devs and help grow and shape the future of our web app focused on helping millions explore the outdoors.

Komoot

????‍???? Got a job listing to share? Here’s how.

???? Don’t tell Satya Nadella..

Fake Windows 11 in Svelte — This is a cute little side project, and the code is available too. The most common complaint I’ve seen is that it’s actually more responsive than the real Windows.. ???? Be sure to check out both ‘VS Code’ and ‘Microsoft Edge’ in this environment.

Yashash Pugalia

???? Prefer Windows XP? Maybe RebornXP is more for you. Complete with the classic starting up sound!

Flatlogic Admin Templates banner

jQuery 3.6.3 Released: A Quick Selector Fix

Last week, we released jQuery 3.6.2. There were several changes in that release, but the most important one addressed an issue with some new selectors introduced in most browsers, like :has(). We wanted to release jQuery 3.6.3 quickly because an issue was reported that revealed a problem with our original fix. More details on that below.

As usual, the release is available on our cdn and the npm package manager. Other third party CDNs will probably have it soon as well, but remember that we don’t control their release schedules and they will need some time. Here are the highlights for jQuery 3.6.3.

Using CSS.supports the right way

After the issue with :has that was fixed in jQuery 3.6.2, we started using CSS.supports( “selector(SELECTOR)”) to determine whether a selector would be valid if passed directly to querySelectorAll. When CSS.supports returned false, jQuery would then fall back to its own selector engine (Sizzle). Apparently, our implementation had a bug. In CSS.supports( “selector(SELECTOR)”), SELECTOR needed to be a <complex-selector> and not a <complex-selector-list>. For example:

CSS.supports(“selector(div)”); // true
CSS.supports(“selector(div, span)”); // false

This meant that all complex selector lists were passed through Sizzle instead of querySelectorAll. That’s not necessarily a problem in most cases, but it does mean that some level 4 selectors that were supported in browsers but not in Sizzle, like :valid, no longer worked if it was part of a selector list (e.g. “input:valid, div”). It should be noted this currently only affects Firefox, but it will be true in all browsers as they roll out changes to CSS.supports.

This has now been fixed in jQuery 3.6.3 and it is the only functional change in this release.

Upgrading

We do not expect compatibility issues when upgrading from a jQuery 3.0+ version. To upgrade, have a look at the new 3.5 Upgrade Guide. If you haven’t yet upgraded to jQuery 3+, first have a look at the 3.0 Upgrade Guide.

The jQuery Migrate plugin will help you to identify compatibility issues in your code. Please try out this new release and let us know about any issues you experienced.

If you can’t yet upgrade to 3.5+, Daniel Ruf has kindly provided patches for previous jQuery versions.

Download

You can get the files from the jQuery CDN, or link to them directly:

https://code.jquery.com/jquery-3.6.3.js

https://code.jquery.com/jquery-3.6.3.min.js

You can also get this release from npm:

npm install [email protected]

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version. These files are also available in the npm package and on the CDN:

https://code.jquery.com/jquery-3.6.3.slim.js

https://code.jquery.com/jquery-3.6.3.slim.min.js

These updates are already available as the current versions on npm and Bower. Information on all the ways to get jQuery is available at https://jquery.com/download/. Public CDNs receive their copies today, please give them a few days to post the files. If you’re anxious to get a quick start, use the files on our CDN until they have a chance to update.

Thanks

Thank you to all of you who participated in this release by submitting patches, reporting bugs, or testing, including Michal Golebiowski-Owczarek and the whole jQuery team.

Changelog

Full changelog: 3.6.3

Build

remove stale Insight package from custom builds (81d5bd17)
Updating the 3.x-stable version to 3.6.3-pre. (2c5b47c4)

Selector

Update Sizzle from 2.3.8 to 2.3.9 (#5177, 8989500e)

Flatlogic Admin Templates banner

Adding feature flags to an ASP.NET Core app

This post is about Adding feature flags to an ASP.NET Core app.Feature flags (also known as feature toggles or feature switches) are a software development technique that turns certain functionality on and off during runtime, without deploying new code. In this post we will discuss about flags using appsettings.json file. I am using an ASP.NET Core MVC project, you can do it for any .NET Core project like Razor Web Apps, or Web APIs.

First we need to add reference of Microsoft.FeatureManagement.AspNetCore nuget package – This package created by Microsoft, it will support creation of simple on/off feature flags as well as complex conditional flags. Once this package added, we need to add the following code to inject the Feature Manager instance to the http pipeline.

using Microsoft.FeatureManagement;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();

builder.Services.AddFeatureManagement();

var app = builder.Build();

Next we need to create a FeatureManagement section in the appsettings.json with feature with a boolean value like this.

“FeatureManagement”: {
“WelcomeMessage”: false
}

Now we are ready with feature toggle, let us write code to manage it from the controller. In the controller, ASP.NET Core runtime will inject an instance of the IFeatureManager. And in this interface we can check whether a feature is enabled or not using the IsEnabledAsync method. So for our feature we can do it like this.

public async Task<IActionResult> IndexAsync()
{
if(await _featureManager.IsEnabledAsync(“WelcomeMessage”))
{
ViewData[“WelcomeMessage”] = “Welcome to the Feature Demo app.”;
}
return View();
}

And in the View we can write the following code.

@if (ViewData[“WelcomeMessage”] != null)
{
<div class=“alert alert-primary” role=“alert”>
@ViewData[“WelcomeMessage”]
</div>
}

Run the application, the alert will not be displayed. You can change the WelcomeMessage to true and refresh the page – it will display the bootstrap alert.

This way you can start introducing Feature Flags or Feature Toggles in ASP.NET Core MVC app. As you may already noticed the Feature Management library built on top of the configuration system of .NET Core. So it will support any configuration sources as Feature flags source. Microsoft Azure provides Azure App Configuration service which helps to implement feature flags for cloud native apps.

Happy Programming 🙂Flatlogic Admin Templates banner

.NET IdempotentAPI 1.0.0 Release Candidate

Introduction

A distributed system consists of multiple components located on different networked computers, which communicate and coordinate their actions by passing messages to one another from any system. Fault-tolerant applications can continue operating despite the system, hardware, and network faults of one or more components.

Idempotency in Web APIs ensures that the API works correctly (as designed) even when consumers (clients) send the same request multiple times. To simplify the integration of Idempotency in an API project, we could use the IdempotentAPI open-source NuGet library. IdempotentAPI implements an ASP.NET Core attribute (filter) to handle the HTTP write operations (POST and PATCH) to affect only once for the given request data and idempotency key.

In July 2021, we saw how the IdempotentAPI v0.1.0-beta in .NET Nakama (2021, July 4) provides an easy way to develop idempotent Web APIs in .NET Core. Since then, with the community’s help, several issues and improvements have been identified and implemented. The complete journey of the IdempotentAPI is available in the CHANGELOG.md file.

Now, the IdempotentAPI 1.0.0-RC-01 is available with many improvements ?✨. In the following sections, we will see the complete features, details regarding the improvements, the available NuGet packages, and instructions to start using the IdempotentAPI library quickly.

Features

Simple: Support idempotency in your APIs easily with three simple steps 1️⃣2️⃣3️⃣.
? Validations: Performs validation of the request’s hash-key to ensure that the cached response is returned for the same combination of Idempotency Key and Request to prevent accidental misuse.
? Use it anywhere!: IdempotentAPI targets .NET Standard 2.0. So, we can use it in any compatible .NET implementation (.NET Framework, .NET Core, etc.). Click here to see the minimum .NET implementation versions that support each .NET Standard version.
Configurable: Customize the idempotency in your needs.

Configuration Options (see the GitHub repository for more details)
Logging Level configuration.

? Caching Implementation based on your needs.

? DistributedCache: A build-in caching based on the standard IDistributedCache interface.
? FusionCache: A high-performance and robust cache with an optional distributed 2nd layer and advanced features.
… or you could use your implementation ?

Improvement Details

Improving Concurrent Requests Handling

The standard IDistributedCache interface doesn’t support a command to GetOrSet a cached value with atomicity. However, it defines the Get and Set methods. In our previous implementation, we used these two methods without locking (i.e. without grouping into a single logical operation). As a result, we had an issue with concurrent requests with the same idempotency key. The problem was that the controller action could be executed multiple times.

As we can observe in Figure 1, this issue happens when the API Server receives a second request (with the same idempotency key) before we flag the first idempotency key as Inflight (i.e., execution in progress). Thus, racing conditions occur when setting idempotency key as Inflight.

Figure 1. – The issue of executing the controller more than once when concurrent requests with the same idempotency key are performed.

To overcome this issue, we defined the IIdempotencyCache interface and implemented the GetOrSet method, which performs a lock (locally) for each idempotency key (see code below). In Figure 2, we can see how we used the GetOrSet method to execute the controller action only once on concurrent requests with the same idempotency key.

The idea is to use GetOrSet method to set an Inflight object with a dynamic unique id per request when the Get method returns Null (it doesn’t have a value) as a single logical operation. The second call of the GetOrSet will wait for the first call to complete. Thus, only the execution that receives its unique id can continue with the execution of the controller action.

Figure 2. – Concurrent requests with the same idempotency key, execute the controller action only once.

public byte[] GetOrSet(
string key,
byte[] defaultValue,
object? options = null,
CancellationToken token = default)
{
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}

if (options is not null && options is not DistributedCacheEntryOptions)
{
throw new ArgumentNullException(nameof(options));
}

using (var valuelocker = new ValueLocker(key))
{
byte[] cachedData = _distributedCache.Get(key);
if (cachedData is null)
{
_distributedCache.Set(key, defaultValue, (DistributedCacheEntryOptions?)options);
return defaultValue;
}
else
{
return cachedData;
}
}
}

Caching as Implementation Detail

To overcome the concurrent requests with the same idempotency key issue, we defined the IIdempotencyCache interface and implemented the GetOrSet method. This is implemented in our build-in DistributedCache caching project, which is based on the standard IDistributedCache interface.

Our implementation provides basic caching functionality. However, by defining the IIdempotencyCache interface, our IdempotencyAPI logic becomes independent from the caching implementation. Thus, we can support other caching implementations with advanced features, such as the FusionCache.

FusionCache is a high-performance and robust caching .NET library with an optional distributed 2nd layer with advanced features, such as fail-safe mechanism, cache stampede prevention, fine-grained soft/hard timeouts with background factory completion, extensive customizable logging, and more.

BinaryFormatter is Obsolete

The BinaryFormatter serialization methods become obsolete from ASP .NET Core 5.0. In the IdempotentAPI project, the BinaryFormatter was used in the Utils.cs class for serialization and deserialization. As a result, our library was not working in .NET Core 5.0 and later versions unless we enabled the BinaryFormatterSerialization option in the .csproj file.

The recommended action based on the .NET documentation is to stop using BinaryFormatter and use a JSON or XML serializer. In our case, we used the Newtonsoft JsonSerializer, which can include type information when serializing JSON, and read this type of information when deserializing JSON to create the target object with the original types.

In the following JSON example, we can see how the type of information is included in the data.

{
“$type”: “System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib],[System.Object, System.Private.CoreLib]], System.Private.CoreLib”,
“Request.Method”: “POST”,
“Response.StatusCode”: 200,
“Response.Headers”: {
“$type”: “System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib],[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib]], System.Private.CoreLib]], System.Private.CoreLib”,
“myHeader1”: {
“$type”: “System.Collections.Generic.List`1[[System.String, System.Private.CoreLib]], System.Private.CoreLib”,
“$values”: [
“value1-1”,
“value1-2”
]
},
“myHeader2”: {
“$type”: “System.Collections.Generic.List`1[[System.String, System.Private.CoreLib]], System.Private.CoreLib”,
“$values”: [
“value2-1”,
“value2-1”
]
}
}
}

Quick Start

Step 1: Register the Caching Storage

Storing-caching data is necessary for idempotency. Therefore, the IdempotentAPI library needs an implementation of the IIdempotencyCache to be registered in the Program.cs or Startup.cs file depending on the used style (.NET 6.0 or older). The IIdempotencyCache defines the caching storage service for the idempotency needs.

Currently, we support the following two implementations (see the following table). However, you can use your implementation ?. Both implementations support the IDistributedCache either as primary caching storage (requiring registration) or secondary (optional registration).

Thus, we can define our caching storage service in the IDistributedCache, such as in Memory, SQL Server, Redis, NCache, etc. See the Distributed caching in the ASP.NET Core article for more details about the available framework-provided implementations.

IdempotentAPI.Cache
Implementation
Support Concurrent Requests
Primary Cache
2nd-Level Cache
Advanced Features

DistributedCache (Default)

IDistributedCache

FusionCache

Memory Cache

(IDistributedCache)

Choice 1 (Default): IdempotentAPI.Cache.DistributedCache

Install the IdempotentAPI.Cache.DistributedCache via the NuGet UI or the NuGet package manager console.

// Register an implementation of the IDistributedCache.
// For this example, we are using a Memory Cache.
services.AddDistributedMemoryCache();

// Register the IdempotentAPI.Cache.DistributedCache.
services.AddIdempotentAPIUsingDistributedCache();

Choice 2: Registering: IdempotentAPI.Cache.FusionCache

Install the IdempotentAPI.Cache.FusionCache via the NuGet UI or the NuGet package manager console. To use the advanced FusionCache features (2nd-level cache, Fail-Safe, Soft/Hard timeouts, etc.), configure the FusionCacheEntryOptions based on your needs (for more details, visit the FusionCache repository).

// Register the IdempotentAPI.Cache.FusionCache.
// Optionally: Configure the FusionCacheEntryOptions.
services.AddIdempotentAPIUsingFusionCache();

Tip: To use the 2nd-level cache, we should register an implementation for the IDistributedCache and register the FusionCache Serialization (NewtonsoftJson or SystemTextJson). For example, check the following code:

// Register an implementation of the IDistributedCache.
// For this example, we are using Redis.
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = “YOUR CONNECTION STRING HERE, FOR EXAMPLE:localhost:6379”;
});

// Register the FusionCache Serialization (e.g. NewtonsoftJson).
// This is needed for the a 2nd-level cache.
services.AddFusionCacheNewtonsoftJsonSerializer();

// Register the IdempotentAPI.Cache.FusionCache.
// Optionally: Configure the FusionCacheEntryOptions.
services.AddIdempotentAPIUsingFusionCache();

Step 2: Decorate Response Classes as Serializable

The response Data Transfer Objects (DTOs) need to be serialized before caching. For that reason, we will have to decorate the relative DTOs as [Serializable]. For example, see the code below.

using System;

namespace WebApi_3_1.DTOs
{
[Serializable]
public class SimpleResponse
{
public int Id { get; set; }
public string Message { get; set; }
public DateTime CreatedOn { get; set; }
}
}

Step 3: Set Controller Operations as Idempotent

In your Controller class, add the following using statement. Then choose which operations should be Idempotent by setting the [Idempotent()] attribute, either on the controller’s class or each action separately. The following two sections describe these two cases. First, however, we should define the Consumes and Produces attributes on the controller in both cases.

using IdempotentAPI.Filters;

Using the Idempotent Attribute on a Controller’s Class

By using the Idempotent attribute on the API controller’s class, all POST and PATCH actions will work as idempotent operations (requiring the IdempotencyKey header).

[ApiController]
[Route(“[controller]“)]
[Consumes(“application/json”)] // We should define this.
[Produces(“application/json”)] // We should define this.
[Idempotent(Enabled = true)]
public class SimpleController : ControllerBase
{
// …
}

Using the Idempotent Attribute on a Controller’s Action

By using the Idempotent attribute on each action (HTTP POST or PATCH), we can choose which of them should be Idempotent. In addition, we could use the Idempotent attribute to set different options per action.

[HttpPost]
[Idempotent(ExpireHours = 48)]
public IActionResult Post([FromBody] SimpleRequest simpleRequest)
{
// …
}

NuGet Packages

Package Name
Description

IdempotentAPI
The implementation of the IdempotentAPI library.

IdempotentAPI.Cache
Defines the caching abstraction (IIdempotencyCache) that IdempotentAPI is based.

IdempotentAPI.Cache.DistributedCache
The default caching implementation, based on the standard IDistributedCache interface.

IdempotentAPI.Cache.FusionCache
Supports caching via the FusionCache third-party library.

Summary

The IdempotentAPI 1.0.0-RC-01 is available with many improvements ?✨. With the community’s help, several issues and improvements have been identified and implemented. I want to take this opportunity to thank @apchenjun, @fjsosa, @lvzhuye, @RichardGreen-IS2, and @william-keller for your support, ideas, and time to improve this library.

Any help in coding, suggestions, questions, giving a GitHub Star, etc., are welcome ?. If you are using this library, don’t hesitate to contact me. I would be happy to know your use case ?.Flatlogic Admin Templates banner