Explore all Map open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Map

openlayers

6.14.1

cesium

CesiumJS 1.92

mapbox-gl-js

v2.8.2

turf

v6.5.0

react-map-gl

v7.0.11

Popular Libraries in Map

ChineseBQB

by zhaoolee doticonjavascriptdoticon

star image 9910 doticon

🇨🇳 Chinese sticker pack,More joy / 表情包的博物馆, Github最有毒的仓库, 中国表情包大集合, 聚欢乐~

openlayers

by openlayers doticonjavascriptdoticon

star image 8922 doticonBSD-2-Clause

OpenLayers

cesium

by CesiumGS doticonjavascriptdoticon

star image 8557 doticonApache-2.0

An open-source JavaScript library for world-class 3D globes and maps :earth_americas:

mapbox-gl-js

by mapbox doticonjavascriptdoticon

star image 8527 doticonNOASSERTION

Interactive, thoroughly customizable maps in the browser, powered by vector tiles and WebGL

turf

by Turfjs doticonjavascriptdoticon

star image 6754 doticonMIT

A modular geospatial engine written in JavaScript

react-map-gl

by visgl doticontypescriptdoticon

star image 6498 doticonNOASSERTION

React friendly API wrapper around MapboxGL JS

go-datastructures

by Workiva doticongodoticon

star image 6157 doticonApache-2.0

A collection of useful, performant, and threadsafe Go datastructures.

QGIS

by qgis doticonc++doticon

star image 5693 doticonGPL-2.0

QGIS is a free, open source, cross platform (lin/win/mac) geographical information system (GIS)

google-map-react

by google-map-react doticonjavascriptdoticon

star image 5643 doticonMIT

Google map library for react that allows rendering components as markers :tada:

Trending New libraries in Map

prettymaps

by marceloprates doticonjupyter notebookdoticon

star image 5032 doticonMIT

A small set of Python functions to draw pretty maps from OpenStreetMap data. Based on osmnx, matplotlib and shapely libraries.

X-TRACK

by FASTSHIFT doticoncdoticon

star image 3251 doticonGPL-3.0

A GPS bicycle speedometer that supports offline maps and track recording

organicmaps

by organicmaps doticonc++doticon

star image 3208 doticonApache-2.0

🍃 Organic Maps is a free Android & iOS offline maps app for travelers, tourists, hikers, and cyclists. It uses crowd-sourced OpenStreetMap data and is developed with love by MapsWithMe (MapsMe) founders and our community. No ads, no tracking, no data collection, no crapware. Your donations and positive reviews motivate and inspire our small team!

maplibre-gl-js

by maplibre doticontypescriptdoticon

star image 3036 doticonNOASSERTION

The open-source fork of Mapbox GL JS: Interactive maps in the browser, powered by vector tiles and WebGL.

mapus

by alyssaxuu doticonjavascriptdoticon

star image 2178 doticonMIT

A map tool with real-time collaboration 🗺️

felicette

by plant99 doticonpythondoticon

star image 1748 doticonMIT

Satellite imagery for dummies.

Meshtastic-device

by meshtastic doticonc++doticon

star image 1647 doticonGPL-3.0

Device code for the Meshtastic ski/hike/fly/customizable open GPS radio

leafmap

by giswqs doticonpythondoticon

star image 1195 doticonMIT

A Python package for interactive mapping and geospatial analysis with minimal coding in a Jupyter environment

earthengine-py-notebooks

by giswqs doticonjupyter notebookdoticon

star image 913 doticonMIT

A collection of 360+ Jupyter Python notebook examples for using Google Earth Engine with interactive mapping

Top Authors in Map

1

mapbox

110 Libraries

star icon29178

2

Esri

42 Libraries

star icon4274

3

osmlab

34 Libraries

star icon1699

4

giswqs

24 Libraries

star icon3539

5

digidem

21 Libraries

star icon697

6

openstreetmap

18 Libraries

star icon6281

7

developmentseed

16 Libraries

star icon474

8

iandees

16 Libraries

star icon184

9

makinacorpus

16 Libraries

star icon1312

10

perliedman

15 Libraries

star icon767

1

110 Libraries

star icon29178

2

42 Libraries

star icon4274

3

34 Libraries

star icon1699

4

24 Libraries

star icon3539

5

21 Libraries

star icon697

6

18 Libraries

star icon6281

7

16 Libraries

star icon474

8

16 Libraries

star icon184

9

16 Libraries

star icon1312

10

15 Libraries

star icon767

Trending Kits in Map

PHP Map Libraries are designed to help developers display and manipulate maps on web pages using PHP. All PHP libraries offer ways to display maps on web pages. They provide different map styles, like satellite, terrain, and street views. These libraries offer customization options like changing map styles, adding custom data overlays, and customizing markers.  


Most PHP map libraries will let developers place markers on the map, which will indicate points of interest or for identifying locations. We can customize those markers with different labels or icons. Geocoding will help convert addresses into latitude and longitude coordinates, and these libraries offer these features for developers to pinpoint locations on the map. These libraries offer functionality for helping users in planning trips and getting directions. They offer support when you want to add layers to the map. They offer APIs for developers to integrate the map functionality into their applications.  


Here is the list of the top 7 PHP Map Libraries handpicked to help developers integrate their maps with their applications.  

GeoIP2-php: 

  • Is a PHP library that offers an easy-to-use and simple interface for MaxMind’s GeoIP2 database. 
  • Offers accurate and detailed information about the geographic location of IP addresses. 
  • Allows PHP developers to easily integrate MaxMind’s GeoIP2 databases directly into their web applications.  

phpgeo: 

  • Is a PHP library that offers an easy-to-use interface to work with geographic coordinates like latitude and longitude.  
  • Includes classes for working with bounding boxes, polygons, points, and conversion between coordinate systems and distance calculation.  
  • Is designed to be lightweight and easy to use, making it an excellent choice for developers who need to work with geographic coordinates in their PHP applications.  

geotools: 

  • Is a PHP library that offers various tools for working with geographic data like geographic projections, geometrics, and coordinates. 
  • Includes classes for workings with polygons, points, lines, and other geometric shapes and methods for transforming between different coordinate projections and systems. 
  • Is a useful tool for PHP developers who want to work with geographic data in their applications.  

Valinor: 

  • Is a PHP library that offers various tools for working with geographic spatial databases and data.  
  • Includes support for spatial data types and functions and integration with popular spatial databases like PostGIS.  
  • Includes classes for working with lines, points, polygons, and other shapes and methods for calculating areas, the intersection between shapes, and distances.  

geoPHP: 

  • Is a PHP library that offers tools to work with geographic data like geographic geometrics, projections, and coordinates.  
  • Support for different coordinate projections and systems, including popular systems like UTM, Lambert Conformal Conic, and WGS84.  
  • Supports various coordinate projections and systems and their geometry transformation and class methods, making it a powerful tool for working with geographic data. 

GeocoderLaravel: 

  • Is a PHP library that offers geocode and reverse geocoding services to Laravel applications. 
  • Uses popular geocoding services like Bing Maps, OpenStreetMap, and Google Maps for converting place names or addresses into geographic coordinates and vice versa. 
  • Includes caching functionality that helps improve the performance of geocoding requests by caching the results of previous requests.  

google-maps: 

  • Is a PHP client library for the Google Maps API, making it easy to integrate into your application.  
  • Offers a straightforward way to access different services offered by Google Maps, like directions, distance matrix, and geocoding.  
  • Offers support for directions that allows developers to retrieve directions between two or more locations.  

JavaScript is a powerful scripting language for creating interactive websites and web applications. JavaScript mapping and geolocation libraries help to create interactive, feature-rich web applications that can use geographical data to interact with the user and the environment. These libraries make it possible to create interactive maps, visualizations, and other data-driven applications. 


These libraries are built around the W3C Geolocation API, a set of JavaScript functions that allow developers to access location information from devices such as GPS, cell phones, or computers. The API determines the user's current location, tracks their movement, and calculates the distances between two locations. It provides developers with a consistent and reliable way to access location-based data. The API is also compatible with most modern web browsers, making it easy to integrate into existing websites and applications. Some JavaScript mapping/geolocation libraries also use the HTML Geolocation API to locate the user's position. The API provides a way for web browsers to access location information from the user's device. When the user grants permission, the API will return the user's current position, which can then be used to create a map or locate nearby points of interest. The library can then be used to render the map on the page or search for nearby locations. 


Some of the most popular libraries to work with the APIs include geolocation, Mapbox, OpenLayers, react-native-boilerplate, Turf.js, appc-sample-geocoder, Citibike, travelAdvisor, Tangram, and TwitterMap. Mapbox and OpenLayers are powerful tools that provide other mapping services like street maps, satellite images, and terrain data. Turf.js performs geospatial analysis; Tangram is a library for creating 3D maps.


Check out the below list to find the best top 10 JavaScript Mapping/Geolocation Libraries for your app development;

Trending Discussions on Map

The unauthenticated git protocol on port 9418 is no longer supported

Emulate BTreeMap::pop_last in stable Rust

Error when trying to run my React Native app on Android

throwError(error) is now deprecated, but there is no new Error(HttpErrorResponse)

TypeError: Cannot read properties of undefined (reading 'id')

What is the proper evaluation order when assigning a value in a map?

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in the package.json of a module in node_modules

Build Warning : Mapping new ns to old ns

Python 3.10 pattern matching (PEP 634) - wildcard in string

Command CompileSwiftSources failed with a nonzero exit code XCode 13

QUESTION

The unauthenticated git protocol on port 9418 is no longer supported

Asked 2022-Mar-27 at 13:23

I have been using github actions for quite sometime but today my deployments started failing. Below is the error from github action logs

1Command: git
2Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
3Directory: /home/runner/work/stackstream-fe/stackstream-fe
4Output:
5fatal: remote error: 
6  The unauthenticated git protocol on port 9418 is no longer supported.
7

Upon investigation, it appears that below section in my yml file is causing the issue.

1Command: git
2Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
3Directory: /home/runner/work/stackstream-fe/stackstream-fe
4Output:
5fatal: remote error: 
6  The unauthenticated git protocol on port 9418 is no longer supported.
7    - name: Installing modules
8      run: yarn install
9

I have looked into this change log but can't seem to comprehend the issue.

Additional Details: Server: EC2 Instance Github actions steps:

1Command: git
2Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
3Directory: /home/runner/work/stackstream-fe/stackstream-fe
4Output:
5fatal: remote error: 
6  The unauthenticated git protocol on port 9418 is no longer supported.
7    - name: Installing modules
8      run: yarn install
9  steps:
10  - name: Checkout
11    uses: actions/checkout@v2
12
13  - id: vars
14    run: |
15      if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream"  ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
16
17  - uses: pCYSl5EDgo/cat@master
18    id: slack
19    with:
20      path: .github/workflows/slack.txt
21
22  - name: Slack Start Notification
23    uses: 8398a7/action-slack@v3
24    env:
25      SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
26      ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
27      COLOR: good
28      STATUS: '`Started`'
29    with:
30      status: custom
31      fields: workflow,job,commit,repo,ref,author,took
32      custom_payload: |
33        ${{ steps.slack.outputs.text }}
34
35  - name: Installing modules
36    env:
37      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
38    run: yarn install
39
40  - name: Create Frontend Build
41    env:
42      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
43    run: yarn build
44
45  - name: Deploy to Frontend Server DEV
46    if: ${{ contains(github.ref, 'dev') }}
47    uses: easingthemes/ssh-deploy@v2.1.5
48    env:
49      SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
50      ARGS: '-rltgoDzvO --delete'
51      SOURCE: 'deploy/'
52      REMOTE_HOST: ${{ secrets.DEV_HOST }}
53      REMOTE_USER: plyfolio-dev
54      TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
55

package.json file

1Command: git
2Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
3Directory: /home/runner/work/stackstream-fe/stackstream-fe
4Output:
5fatal: remote error: 
6  The unauthenticated git protocol on port 9418 is no longer supported.
7    - name: Installing modules
8      run: yarn install
9  steps:
10  - name: Checkout
11    uses: actions/checkout@v2
12
13  - id: vars
14    run: |
15      if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream"  ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
16
17  - uses: pCYSl5EDgo/cat@master
18    id: slack
19    with:
20      path: .github/workflows/slack.txt
21
22  - name: Slack Start Notification
23    uses: 8398a7/action-slack@v3
24    env:
25      SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
26      ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
27      COLOR: good
28      STATUS: '`Started`'
29    with:
30      status: custom
31      fields: workflow,job,commit,repo,ref,author,took
32      custom_payload: |
33        ${{ steps.slack.outputs.text }}
34
35  - name: Installing modules
36    env:
37      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
38    run: yarn install
39
40  - name: Create Frontend Build
41    env:
42      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
43    run: yarn build
44
45  - name: Deploy to Frontend Server DEV
46    if: ${{ contains(github.ref, 'dev') }}
47    uses: easingthemes/ssh-deploy@v2.1.5
48    env:
49      SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
50      ARGS: '-rltgoDzvO --delete'
51      SOURCE: 'deploy/'
52      REMOTE_HOST: ${{ secrets.DEV_HOST }}
53      REMOTE_USER: plyfolio-dev
54      TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
55   {
56  "name": "stackstream-fe",
57  "version": "1.0.0",
58  "authors": [
59    "fayyaznofal@gmail.com"
60  ],
61  "private": true,
62  "dependencies": {
63    "@fortawesome/fontawesome-svg-core": "^1.2.34",
64    "@fortawesome/free-solid-svg-icons": "^5.15.2",
65    "@fortawesome/react-fontawesome": "^0.1.14",
66    "@fullcalendar/bootstrap": "^5.5.0",
67    "@fullcalendar/core": "^5.5.0",
68    "@fullcalendar/daygrid": "^5.5.0",
69    "@fullcalendar/interaction": "^5.5.0",
70    "@fullcalendar/react": "^5.5.0",
71    "@lourenci/react-kanban": "^2.1.0",
72    "@redux-saga/simple-saga-monitor": "^1.1.2",
73    "@testing-library/jest-dom": "^5.11.9",
74    "@testing-library/react": "^11.2.3",
75    "@testing-library/user-event": "^12.6.0",
76    "@toast-ui/react-chart": "^1.0.2",
77    "@types/jest": "^26.0.14",
78    "@types/node": "^14.10.3",
79    "@types/react": "^16.9.49",
80    "@types/react-dom": "^16.9.8",
81    "@vtaits/react-color-picker": "^0.1.1",
82    "apexcharts": "^3.23.1",
83    "availity-reactstrap-validation": "^2.7.0",
84    "axios": "^0.21.1",
85    "axios-mock-adapter": "^1.19.0",
86    "axios-progress-bar": "^1.2.0",
87    "bootstrap": "^5.0.0-beta2",
88    "chart.js": "^2.9.4",
89    "chartist": "^0.11.4",
90    "classnames": "^2.2.6",
91    "components": "^0.1.0",
92    "dotenv": "^8.2.0",
93    "draft-js": "^0.11.7",
94    "echarts": "^4.9.0",
95    "echarts-for-react": "^2.0.16",
96    "firebase": "^8.2.3",
97    "google-maps-react": "^2.0.6",
98    "history": "^4.10.1",
99    "i": "^0.3.6",
100    "i18next": "^19.8.4",
101    "i18next-browser-languagedetector": "^6.0.1",
102    "jsonwebtoken": "^8.5.1",
103    "leaflet": "^1.7.1",
104    "lodash": "^4.17.21",
105    "lodash.clonedeep": "^4.5.0",
106    "lodash.get": "^4.4.2",
107    "metismenujs": "^1.2.1",
108    "mkdirp": "^1.0.4",
109    "moment": "2.29.1",
110    "moment-timezone": "^0.5.32",
111    "nouislider-react": "^3.3.9",
112    "npm": "^7.6.3",
113    "prop-types": "^15.7.2",
114    "query-string": "^6.14.0",
115    "react": "^16.13.1",
116    "react-apexcharts": "^1.3.7",
117    "react-auth-code-input": "^1.0.0",
118    "react-avatar": "^3.10.0",
119    "react-bootstrap": "^1.5.0",
120    "react-bootstrap-editable": "^0.8.2",
121    "react-bootstrap-sweetalert": "^5.2.0",
122    "react-bootstrap-table-next": "^4.0.3",
123    "react-bootstrap-table2-editor": "^1.4.0",
124    "react-bootstrap-table2-paginator": "^2.1.2",
125    "react-bootstrap-table2-toolkit": "^2.1.3",
126    "react-chartist": "^0.14.3",
127    "react-chartjs-2": "^2.11.1",
128    "react-color": "^2.19.3",
129    "react-confirm-alert": "^2.7.0",
130    "react-content-loader": "^6.0.1",
131    "react-countdown": "^2.3.1",
132    "react-countup": "^4.3.3",
133    "react-cropper": "^2.1.4",
134    "react-data-table-component": "^6.11.8",
135    "react-date-picker": "^8.0.6",
136    "react-datepicker": "^3.4.1",
137    "react-dom": "^16.13.1",
138    "react-draft-wysiwyg": "^1.14.5",
139    "react-drag-listview": "^0.1.8",
140    "react-drawer": "^1.3.4",
141    "react-dropzone": "^11.2.4",
142    "react-dual-listbox": "^2.0.0",
143    "react-facebook-login": "^4.1.1",
144    "react-flatpickr": "^3.10.6",
145    "react-google-login": "^5.2.2",
146    "react-hook-form": "^7.15.2",
147    "react-i18next": "^11.8.5",
148    "react-icons": "^4.2.0",
149    "react-image-lightbox": "^5.1.1",
150    "react-input-mask": "^2.0.4",
151    "react-jvectormap": "^0.0.16",
152    "react-leaflet": "^3.0.5",
153    "react-meta-tags": "^1.0.1",
154    "react-modal-video": "^1.2.6",
155    "react-notifications": "^1.7.2",
156    "react-number-format": "^4.7.3",
157    "react-perfect-scrollbar": "^1.5.8",
158    "react-rangeslider": "^2.2.0",
159    "react-rating": "^2.0.5",
160    "react-rating-tooltip": "^1.1.6",
161    "react-redux": "^7.2.1",
162    "react-responsive-carousel": "^3.2.11",
163    "react-router-dom": "^5.2.0",
164    "react-script": "^2.0.5",
165    "react-scripts": "3.4.3",
166    "react-select": "^4.3.1",
167    "react-sparklines": "^1.7.0",
168    "react-star-ratings": "^2.3.0",
169    "react-super-responsive-table": "^5.2.0",
170    "react-switch": "^6.0.0",
171    "react-table": "^7.6.3",
172    "react-toastify": "^7.0.3",
173    "react-toastr": "^3.0.0",
174    "react-twitter-auth": "0.0.13",
175    "reactstrap": "^8.8.1",
176    "recharts": "^2.0.8",
177    "redux": "^4.0.5",
178    "redux-saga": "^1.1.3",
179    "reselect": "^4.0.0",
180    "sass": "^1.37.5",
181    "simplebar-react": "^2.3.0",
182    "styled": "^1.0.0",
183    "styled-components": "^5.2.1",
184    "toastr": "^2.1.4",
185    "typescript": "^4.0.2",
186    "universal-cookie": "^4.0.4"
187  },
188  "devDependencies": {
189    "@typescript-eslint/eslint-plugin": "^2.27.0",
190    "@typescript-eslint/parser": "^2.27.0",
191    "@typescript-eslint/typescript-estree": "^4.15.2",
192    "eslint-config-prettier": "^6.10.1",
193    "eslint-plugin-prettier": "^3.1.2",
194    "husky": "^4.2.5",
195    "lint-staged": "^10.1.3",
196    "prettier": "^1.19.1",
197    "react-test-renderer": "^16.13.1",
198    "redux-devtools-extension": "^2.13.8",
199    "redux-mock-store": "^1.5.4"
200  },
201  "scripts": {
202    "start": "react-scripts start",
203    "build": "react-scripts build && mv build ./deploy/build",
204    "build-local": "react-scripts build",
205    "test": "react-scripts test",
206    "eject": "react-scripts eject"
207  },
208  "eslintConfig": {
209    "extends": "react-app"
210  },
211  "husky": {
212    "hooks": {
213      "pre-commit": "lint-staged"
214    }
215  },
216  "lint-staged": {
217    "*.{js,ts,tsx}": [
218      "eslint --fix"
219    ]
220  },
221  "browserslist": {
222    "production": [
223      ">0.2%",
224      "not dead",
225      "not op_mini all"
226    ],
227    "development": [
228      "last 1 chrome version",
229      "last 1 firefox version",
230      "last 1 safari version"
231    ]
232  }
233}
234

ANSWER

Answered 2022-Mar-16 at 07:01

First, this error message is indeed expected on Jan. 11th, 2022.
See "Improving Git protocol security on GitHub".

January 11, 2022 Final brownout.

This is the full brownout period where we’ll temporarily stop accepting the deprecated key and signature types, ciphers, and MACs, and the unencrypted Git protocol.
This will help clients discover any lingering use of older keys or old URLs.

Second, check your package.json dependencies for any git:// URL, as in this example, fixed in this PR.

As noted by Jörg W Mittag:

There was a 4-month warning.
The entire Internet has been moving away from unauthenticated, unencrypted protocols for a decade, it's not like this is a huge surprise.

Personally, I consider it less an "issue" and more "detecting unmaintained dependencies".

Plus, this is still only the brownout period, so the protocol will only be disabled for a short period of time, allowing developers to discover the problem.

The permanent shutdown is not until March 15th.


For GitHub Actions:

As in actions/checkout issue 14, you can add as a first step:

1Command: git
2Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
3Directory: /home/runner/work/stackstream-fe/stackstream-fe
4Output:
5fatal: remote error: 
6  The unauthenticated git protocol on port 9418 is no longer supported.
7    - name: Installing modules
8      run: yarn install
9  steps:
10  - name: Checkout
11    uses: actions/checkout@v2
12
13  - id: vars
14    run: |
15      if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream"  ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
16
17  - uses: pCYSl5EDgo/cat@master
18    id: slack
19    with:
20      path: .github/workflows/slack.txt
21
22  - name: Slack Start Notification
23    uses: 8398a7/action-slack@v3
24    env:
25      SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
26      ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
27      COLOR: good
28      STATUS: '`Started`'
29    with:
30      status: custom
31      fields: workflow,job,commit,repo,ref,author,took
32      custom_payload: |
33        ${{ steps.slack.outputs.text }}
34
35  - name: Installing modules
36    env:
37      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
38    run: yarn install
39
40  - name: Create Frontend Build
41    env:
42      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
43    run: yarn build
44
45  - name: Deploy to Frontend Server DEV
46    if: ${{ contains(github.ref, 'dev') }}
47    uses: easingthemes/ssh-deploy@v2.1.5
48    env:
49      SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
50      ARGS: '-rltgoDzvO --delete'
51      SOURCE: 'deploy/'
52      REMOTE_HOST: ${{ secrets.DEV_HOST }}
53      REMOTE_USER: plyfolio-dev
54      TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
55   {
56  "name": "stackstream-fe",
57  "version": "1.0.0",
58  "authors": [
59    "fayyaznofal@gmail.com"
60  ],
61  "private": true,
62  "dependencies": {
63    "@fortawesome/fontawesome-svg-core": "^1.2.34",
64    "@fortawesome/free-solid-svg-icons": "^5.15.2",
65    "@fortawesome/react-fontawesome": "^0.1.14",
66    "@fullcalendar/bootstrap": "^5.5.0",
67    "@fullcalendar/core": "^5.5.0",
68    "@fullcalendar/daygrid": "^5.5.0",
69    "@fullcalendar/interaction": "^5.5.0",
70    "@fullcalendar/react": "^5.5.0",
71    "@lourenci/react-kanban": "^2.1.0",
72    "@redux-saga/simple-saga-monitor": "^1.1.2",
73    "@testing-library/jest-dom": "^5.11.9",
74    "@testing-library/react": "^11.2.3",
75    "@testing-library/user-event": "^12.6.0",
76    "@toast-ui/react-chart": "^1.0.2",
77    "@types/jest": "^26.0.14",
78    "@types/node": "^14.10.3",
79    "@types/react": "^16.9.49",
80    "@types/react-dom": "^16.9.8",
81    "@vtaits/react-color-picker": "^0.1.1",
82    "apexcharts": "^3.23.1",
83    "availity-reactstrap-validation": "^2.7.0",
84    "axios": "^0.21.1",
85    "axios-mock-adapter": "^1.19.0",
86    "axios-progress-bar": "^1.2.0",
87    "bootstrap": "^5.0.0-beta2",
88    "chart.js": "^2.9.4",
89    "chartist": "^0.11.4",
90    "classnames": "^2.2.6",
91    "components": "^0.1.0",
92    "dotenv": "^8.2.0",
93    "draft-js": "^0.11.7",
94    "echarts": "^4.9.0",
95    "echarts-for-react": "^2.0.16",
96    "firebase": "^8.2.3",
97    "google-maps-react": "^2.0.6",
98    "history": "^4.10.1",
99    "i": "^0.3.6",
100    "i18next": "^19.8.4",
101    "i18next-browser-languagedetector": "^6.0.1",
102    "jsonwebtoken": "^8.5.1",
103    "leaflet": "^1.7.1",
104    "lodash": "^4.17.21",
105    "lodash.clonedeep": "^4.5.0",
106    "lodash.get": "^4.4.2",
107    "metismenujs": "^1.2.1",
108    "mkdirp": "^1.0.4",
109    "moment": "2.29.1",
110    "moment-timezone": "^0.5.32",
111    "nouislider-react": "^3.3.9",
112    "npm": "^7.6.3",
113    "prop-types": "^15.7.2",
114    "query-string": "^6.14.0",
115    "react": "^16.13.1",
116    "react-apexcharts": "^1.3.7",
117    "react-auth-code-input": "^1.0.0",
118    "react-avatar": "^3.10.0",
119    "react-bootstrap": "^1.5.0",
120    "react-bootstrap-editable": "^0.8.2",
121    "react-bootstrap-sweetalert": "^5.2.0",
122    "react-bootstrap-table-next": "^4.0.3",
123    "react-bootstrap-table2-editor": "^1.4.0",
124    "react-bootstrap-table2-paginator": "^2.1.2",
125    "react-bootstrap-table2-toolkit": "^2.1.3",
126    "react-chartist": "^0.14.3",
127    "react-chartjs-2": "^2.11.1",
128    "react-color": "^2.19.3",
129    "react-confirm-alert": "^2.7.0",
130    "react-content-loader": "^6.0.1",
131    "react-countdown": "^2.3.1",
132    "react-countup": "^4.3.3",
133    "react-cropper": "^2.1.4",
134    "react-data-table-component": "^6.11.8",
135    "react-date-picker": "^8.0.6",
136    "react-datepicker": "^3.4.1",
137    "react-dom": "^16.13.1",
138    "react-draft-wysiwyg": "^1.14.5",
139    "react-drag-listview": "^0.1.8",
140    "react-drawer": "^1.3.4",
141    "react-dropzone": "^11.2.4",
142    "react-dual-listbox": "^2.0.0",
143    "react-facebook-login": "^4.1.1",
144    "react-flatpickr": "^3.10.6",
145    "react-google-login": "^5.2.2",
146    "react-hook-form": "^7.15.2",
147    "react-i18next": "^11.8.5",
148    "react-icons": "^4.2.0",
149    "react-image-lightbox": "^5.1.1",
150    "react-input-mask": "^2.0.4",
151    "react-jvectormap": "^0.0.16",
152    "react-leaflet": "^3.0.5",
153    "react-meta-tags": "^1.0.1",
154    "react-modal-video": "^1.2.6",
155    "react-notifications": "^1.7.2",
156    "react-number-format": "^4.7.3",
157    "react-perfect-scrollbar": "^1.5.8",
158    "react-rangeslider": "^2.2.0",
159    "react-rating": "^2.0.5",
160    "react-rating-tooltip": "^1.1.6",
161    "react-redux": "^7.2.1",
162    "react-responsive-carousel": "^3.2.11",
163    "react-router-dom": "^5.2.0",
164    "react-script": "^2.0.5",
165    "react-scripts": "3.4.3",
166    "react-select": "^4.3.1",
167    "react-sparklines": "^1.7.0",
168    "react-star-ratings": "^2.3.0",
169    "react-super-responsive-table": "^5.2.0",
170    "react-switch": "^6.0.0",
171    "react-table": "^7.6.3",
172    "react-toastify": "^7.0.3",
173    "react-toastr": "^3.0.0",
174    "react-twitter-auth": "0.0.13",
175    "reactstrap": "^8.8.1",
176    "recharts": "^2.0.8",
177    "redux": "^4.0.5",
178    "redux-saga": "^1.1.3",
179    "reselect": "^4.0.0",
180    "sass": "^1.37.5",
181    "simplebar-react": "^2.3.0",
182    "styled": "^1.0.0",
183    "styled-components": "^5.2.1",
184    "toastr": "^2.1.4",
185    "typescript": "^4.0.2",
186    "universal-cookie": "^4.0.4"
187  },
188  "devDependencies": {
189    "@typescript-eslint/eslint-plugin": "^2.27.0",
190    "@typescript-eslint/parser": "^2.27.0",
191    "@typescript-eslint/typescript-estree": "^4.15.2",
192    "eslint-config-prettier": "^6.10.1",
193    "eslint-plugin-prettier": "^3.1.2",
194    "husky": "^4.2.5",
195    "lint-staged": "^10.1.3",
196    "prettier": "^1.19.1",
197    "react-test-renderer": "^16.13.1",
198    "redux-devtools-extension": "^2.13.8",
199    "redux-mock-store": "^1.5.4"
200  },
201  "scripts": {
202    "start": "react-scripts start",
203    "build": "react-scripts build && mv build ./deploy/build",
204    "build-local": "react-scripts build",
205    "test": "react-scripts test",
206    "eject": "react-scripts eject"
207  },
208  "eslintConfig": {
209    "extends": "react-app"
210  },
211  "husky": {
212    "hooks": {
213      "pre-commit": "lint-staged"
214    }
215  },
216  "lint-staged": {
217    "*.{js,ts,tsx}": [
218      "eslint --fix"
219    ]
220  },
221  "browserslist": {
222    "production": [
223      ">0.2%",
224      "not dead",
225      "not op_mini all"
226    ],
227    "development": [
228      "last 1 chrome version",
229      "last 1 firefox version",
230      "last 1 safari version"
231    ]
232  }
233}
234    - name: Fix up git URLs
235      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
236

That will change any git://github.com/ into https://github.com/.

For local projects

For all your repositories, you can set:

1Command: git
2Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
3Directory: /home/runner/work/stackstream-fe/stackstream-fe
4Output:
5fatal: remote error: 
6  The unauthenticated git protocol on port 9418 is no longer supported.
7    - name: Installing modules
8      run: yarn install
9  steps:
10  - name: Checkout
11    uses: actions/checkout@v2
12
13  - id: vars
14    run: |
15      if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream"  ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
16
17  - uses: pCYSl5EDgo/cat@master
18    id: slack
19    with:
20      path: .github/workflows/slack.txt
21
22  - name: Slack Start Notification
23    uses: 8398a7/action-slack@v3
24    env:
25      SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
26      ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
27      COLOR: good
28      STATUS: '`Started`'
29    with:
30      status: custom
31      fields: workflow,job,commit,repo,ref,author,took
32      custom_payload: |
33        ${{ steps.slack.outputs.text }}
34
35  - name: Installing modules
36    env:
37      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
38    run: yarn install
39
40  - name: Create Frontend Build
41    env:
42      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
43    run: yarn build
44
45  - name: Deploy to Frontend Server DEV
46    if: ${{ contains(github.ref, 'dev') }}
47    uses: easingthemes/ssh-deploy@v2.1.5
48    env:
49      SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
50      ARGS: '-rltgoDzvO --delete'
51      SOURCE: 'deploy/'
52      REMOTE_HOST: ${{ secrets.DEV_HOST }}
53      REMOTE_USER: plyfolio-dev
54      TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
55   {
56  "name": "stackstream-fe",
57  "version": "1.0.0",
58  "authors": [
59    "fayyaznofal@gmail.com"
60  ],
61  "private": true,
62  "dependencies": {
63    "@fortawesome/fontawesome-svg-core": "^1.2.34",
64    "@fortawesome/free-solid-svg-icons": "^5.15.2",
65    "@fortawesome/react-fontawesome": "^0.1.14",
66    "@fullcalendar/bootstrap": "^5.5.0",
67    "@fullcalendar/core": "^5.5.0",
68    "@fullcalendar/daygrid": "^5.5.0",
69    "@fullcalendar/interaction": "^5.5.0",
70    "@fullcalendar/react": "^5.5.0",
71    "@lourenci/react-kanban": "^2.1.0",
72    "@redux-saga/simple-saga-monitor": "^1.1.2",
73    "@testing-library/jest-dom": "^5.11.9",
74    "@testing-library/react": "^11.2.3",
75    "@testing-library/user-event": "^12.6.0",
76    "@toast-ui/react-chart": "^1.0.2",
77    "@types/jest": "^26.0.14",
78    "@types/node": "^14.10.3",
79    "@types/react": "^16.9.49",
80    "@types/react-dom": "^16.9.8",
81    "@vtaits/react-color-picker": "^0.1.1",
82    "apexcharts": "^3.23.1",
83    "availity-reactstrap-validation": "^2.7.0",
84    "axios": "^0.21.1",
85    "axios-mock-adapter": "^1.19.0",
86    "axios-progress-bar": "^1.2.0",
87    "bootstrap": "^5.0.0-beta2",
88    "chart.js": "^2.9.4",
89    "chartist": "^0.11.4",
90    "classnames": "^2.2.6",
91    "components": "^0.1.0",
92    "dotenv": "^8.2.0",
93    "draft-js": "^0.11.7",
94    "echarts": "^4.9.0",
95    "echarts-for-react": "^2.0.16",
96    "firebase": "^8.2.3",
97    "google-maps-react": "^2.0.6",
98    "history": "^4.10.1",
99    "i": "^0.3.6",
100    "i18next": "^19.8.4",
101    "i18next-browser-languagedetector": "^6.0.1",
102    "jsonwebtoken": "^8.5.1",
103    "leaflet": "^1.7.1",
104    "lodash": "^4.17.21",
105    "lodash.clonedeep": "^4.5.0",
106    "lodash.get": "^4.4.2",
107    "metismenujs": "^1.2.1",
108    "mkdirp": "^1.0.4",
109    "moment": "2.29.1",
110    "moment-timezone": "^0.5.32",
111    "nouislider-react": "^3.3.9",
112    "npm": "^7.6.3",
113    "prop-types": "^15.7.2",
114    "query-string": "^6.14.0",
115    "react": "^16.13.1",
116    "react-apexcharts": "^1.3.7",
117    "react-auth-code-input": "^1.0.0",
118    "react-avatar": "^3.10.0",
119    "react-bootstrap": "^1.5.0",
120    "react-bootstrap-editable": "^0.8.2",
121    "react-bootstrap-sweetalert": "^5.2.0",
122    "react-bootstrap-table-next": "^4.0.3",
123    "react-bootstrap-table2-editor": "^1.4.0",
124    "react-bootstrap-table2-paginator": "^2.1.2",
125    "react-bootstrap-table2-toolkit": "^2.1.3",
126    "react-chartist": "^0.14.3",
127    "react-chartjs-2": "^2.11.1",
128    "react-color": "^2.19.3",
129    "react-confirm-alert": "^2.7.0",
130    "react-content-loader": "^6.0.1",
131    "react-countdown": "^2.3.1",
132    "react-countup": "^4.3.3",
133    "react-cropper": "^2.1.4",
134    "react-data-table-component": "^6.11.8",
135    "react-date-picker": "^8.0.6",
136    "react-datepicker": "^3.4.1",
137    "react-dom": "^16.13.1",
138    "react-draft-wysiwyg": "^1.14.5",
139    "react-drag-listview": "^0.1.8",
140    "react-drawer": "^1.3.4",
141    "react-dropzone": "^11.2.4",
142    "react-dual-listbox": "^2.0.0",
143    "react-facebook-login": "^4.1.1",
144    "react-flatpickr": "^3.10.6",
145    "react-google-login": "^5.2.2",
146    "react-hook-form": "^7.15.2",
147    "react-i18next": "^11.8.5",
148    "react-icons": "^4.2.0",
149    "react-image-lightbox": "^5.1.1",
150    "react-input-mask": "^2.0.4",
151    "react-jvectormap": "^0.0.16",
152    "react-leaflet": "^3.0.5",
153    "react-meta-tags": "^1.0.1",
154    "react-modal-video": "^1.2.6",
155    "react-notifications": "^1.7.2",
156    "react-number-format": "^4.7.3",
157    "react-perfect-scrollbar": "^1.5.8",
158    "react-rangeslider": "^2.2.0",
159    "react-rating": "^2.0.5",
160    "react-rating-tooltip": "^1.1.6",
161    "react-redux": "^7.2.1",
162    "react-responsive-carousel": "^3.2.11",
163    "react-router-dom": "^5.2.0",
164    "react-script": "^2.0.5",
165    "react-scripts": "3.4.3",
166    "react-select": "^4.3.1",
167    "react-sparklines": "^1.7.0",
168    "react-star-ratings": "^2.3.0",
169    "react-super-responsive-table": "^5.2.0",
170    "react-switch": "^6.0.0",
171    "react-table": "^7.6.3",
172    "react-toastify": "^7.0.3",
173    "react-toastr": "^3.0.0",
174    "react-twitter-auth": "0.0.13",
175    "reactstrap": "^8.8.1",
176    "recharts": "^2.0.8",
177    "redux": "^4.0.5",
178    "redux-saga": "^1.1.3",
179    "reselect": "^4.0.0",
180    "sass": "^1.37.5",
181    "simplebar-react": "^2.3.0",
182    "styled": "^1.0.0",
183    "styled-components": "^5.2.1",
184    "toastr": "^2.1.4",
185    "typescript": "^4.0.2",
186    "universal-cookie": "^4.0.4"
187  },
188  "devDependencies": {
189    "@typescript-eslint/eslint-plugin": "^2.27.0",
190    "@typescript-eslint/parser": "^2.27.0",
191    "@typescript-eslint/typescript-estree": "^4.15.2",
192    "eslint-config-prettier": "^6.10.1",
193    "eslint-plugin-prettier": "^3.1.2",
194    "husky": "^4.2.5",
195    "lint-staged": "^10.1.3",
196    "prettier": "^1.19.1",
197    "react-test-renderer": "^16.13.1",
198    "redux-devtools-extension": "^2.13.8",
199    "redux-mock-store": "^1.5.4"
200  },
201  "scripts": {
202    "start": "react-scripts start",
203    "build": "react-scripts build && mv build ./deploy/build",
204    "build-local": "react-scripts build",
205    "test": "react-scripts test",
206    "eject": "react-scripts eject"
207  },
208  "eslintConfig": {
209    "extends": "react-app"
210  },
211  "husky": {
212    "hooks": {
213      "pre-commit": "lint-staged"
214    }
215  },
216  "lint-staged": {
217    "*.{js,ts,tsx}": [
218      "eslint --fix"
219    ]
220  },
221  "browserslist": {
222    "production": [
223      ">0.2%",
224      "not dead",
225      "not op_mini all"
226    ],
227    "development": [
228      "last 1 chrome version",
229      "last 1 firefox version",
230      "last 1 safari version"
231    ]
232  }
233}
234    - name: Fix up git URLs
235      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
236git config --global url."https://github.com/".insteadOf git://github.com/
237

You can also use SSH, but GitHub Security reminds us that, as of March 15th, 2022, GitHub stopped accepting DSA keys. RSA keys uploaded after Nov 2, 2021 will work only with SHA-2 signatures.
The deprecated MACs, ciphers, and unencrypted Git protocol are permanently disabled.

So this (with the right key) would work:

1Command: git
2Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
3Directory: /home/runner/work/stackstream-fe/stackstream-fe
4Output:
5fatal: remote error: 
6  The unauthenticated git protocol on port 9418 is no longer supported.
7    - name: Installing modules
8      run: yarn install
9  steps:
10  - name: Checkout
11    uses: actions/checkout@v2
12
13  - id: vars
14    run: |
15      if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream"  ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
16
17  - uses: pCYSl5EDgo/cat@master
18    id: slack
19    with:
20      path: .github/workflows/slack.txt
21
22  - name: Slack Start Notification
23    uses: 8398a7/action-slack@v3
24    env:
25      SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
26      ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
27      COLOR: good
28      STATUS: '`Started`'
29    with:
30      status: custom
31      fields: workflow,job,commit,repo,ref,author,took
32      custom_payload: |
33        ${{ steps.slack.outputs.text }}
34
35  - name: Installing modules
36    env:
37      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
38    run: yarn install
39
40  - name: Create Frontend Build
41    env:
42      REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
43    run: yarn build
44
45  - name: Deploy to Frontend Server DEV
46    if: ${{ contains(github.ref, 'dev') }}
47    uses: easingthemes/ssh-deploy@v2.1.5
48    env:
49      SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
50      ARGS: '-rltgoDzvO --delete'
51      SOURCE: 'deploy/'
52      REMOTE_HOST: ${{ secrets.DEV_HOST }}
53      REMOTE_USER: plyfolio-dev
54      TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
55   {
56  "name": "stackstream-fe",
57  "version": "1.0.0",
58  "authors": [
59    "fayyaznofal@gmail.com"
60  ],
61  "private": true,
62  "dependencies": {
63    "@fortawesome/fontawesome-svg-core": "^1.2.34",
64    "@fortawesome/free-solid-svg-icons": "^5.15.2",
65    "@fortawesome/react-fontawesome": "^0.1.14",
66    "@fullcalendar/bootstrap": "^5.5.0",
67    "@fullcalendar/core": "^5.5.0",
68    "@fullcalendar/daygrid": "^5.5.0",
69    "@fullcalendar/interaction": "^5.5.0",
70    "@fullcalendar/react": "^5.5.0",
71    "@lourenci/react-kanban": "^2.1.0",
72    "@redux-saga/simple-saga-monitor": "^1.1.2",
73    "@testing-library/jest-dom": "^5.11.9",
74    "@testing-library/react": "^11.2.3",
75    "@testing-library/user-event": "^12.6.0",
76    "@toast-ui/react-chart": "^1.0.2",
77    "@types/jest": "^26.0.14",
78    "@types/node": "^14.10.3",
79    "@types/react": "^16.9.49",
80    "@types/react-dom": "^16.9.8",
81    "@vtaits/react-color-picker": "^0.1.1",
82    "apexcharts": "^3.23.1",
83    "availity-reactstrap-validation": "^2.7.0",
84    "axios": "^0.21.1",
85    "axios-mock-adapter": "^1.19.0",
86    "axios-progress-bar": "^1.2.0",
87    "bootstrap": "^5.0.0-beta2",
88    "chart.js": "^2.9.4",
89    "chartist": "^0.11.4",
90    "classnames": "^2.2.6",
91    "components": "^0.1.0",
92    "dotenv": "^8.2.0",
93    "draft-js": "^0.11.7",
94    "echarts": "^4.9.0",
95    "echarts-for-react": "^2.0.16",
96    "firebase": "^8.2.3",
97    "google-maps-react": "^2.0.6",
98    "history": "^4.10.1",
99    "i": "^0.3.6",
100    "i18next": "^19.8.4",
101    "i18next-browser-languagedetector": "^6.0.1",
102    "jsonwebtoken": "^8.5.1",
103    "leaflet": "^1.7.1",
104    "lodash": "^4.17.21",
105    "lodash.clonedeep": "^4.5.0",
106    "lodash.get": "^4.4.2",
107    "metismenujs": "^1.2.1",
108    "mkdirp": "^1.0.4",
109    "moment": "2.29.1",
110    "moment-timezone": "^0.5.32",
111    "nouislider-react": "^3.3.9",
112    "npm": "^7.6.3",
113    "prop-types": "^15.7.2",
114    "query-string": "^6.14.0",
115    "react": "^16.13.1",
116    "react-apexcharts": "^1.3.7",
117    "react-auth-code-input": "^1.0.0",
118    "react-avatar": "^3.10.0",
119    "react-bootstrap": "^1.5.0",
120    "react-bootstrap-editable": "^0.8.2",
121    "react-bootstrap-sweetalert": "^5.2.0",
122    "react-bootstrap-table-next": "^4.0.3",
123    "react-bootstrap-table2-editor": "^1.4.0",
124    "react-bootstrap-table2-paginator": "^2.1.2",
125    "react-bootstrap-table2-toolkit": "^2.1.3",
126    "react-chartist": "^0.14.3",
127    "react-chartjs-2": "^2.11.1",
128    "react-color": "^2.19.3",
129    "react-confirm-alert": "^2.7.0",
130    "react-content-loader": "^6.0.1",
131    "react-countdown": "^2.3.1",
132    "react-countup": "^4.3.3",
133    "react-cropper": "^2.1.4",
134    "react-data-table-component": "^6.11.8",
135    "react-date-picker": "^8.0.6",
136    "react-datepicker": "^3.4.1",
137    "react-dom": "^16.13.1",
138    "react-draft-wysiwyg": "^1.14.5",
139    "react-drag-listview": "^0.1.8",
140    "react-drawer": "^1.3.4",
141    "react-dropzone": "^11.2.4",
142    "react-dual-listbox": "^2.0.0",
143    "react-facebook-login": "^4.1.1",
144    "react-flatpickr": "^3.10.6",
145    "react-google-login": "^5.2.2",
146    "react-hook-form": "^7.15.2",
147    "react-i18next": "^11.8.5",
148    "react-icons": "^4.2.0",
149    "react-image-lightbox": "^5.1.1",
150    "react-input-mask": "^2.0.4",
151    "react-jvectormap": "^0.0.16",
152    "react-leaflet": "^3.0.5",
153    "react-meta-tags": "^1.0.1",
154    "react-modal-video": "^1.2.6",
155    "react-notifications": "^1.7.2",
156    "react-number-format": "^4.7.3",
157    "react-perfect-scrollbar": "^1.5.8",
158    "react-rangeslider": "^2.2.0",
159    "react-rating": "^2.0.5",
160    "react-rating-tooltip": "^1.1.6",
161    "react-redux": "^7.2.1",
162    "react-responsive-carousel": "^3.2.11",
163    "react-router-dom": "^5.2.0",
164    "react-script": "^2.0.5",
165    "react-scripts": "3.4.3",
166    "react-select": "^4.3.1",
167    "react-sparklines": "^1.7.0",
168    "react-star-ratings": "^2.3.0",
169    "react-super-responsive-table": "^5.2.0",
170    "react-switch": "^6.0.0",
171    "react-table": "^7.6.3",
172    "react-toastify": "^7.0.3",
173    "react-toastr": "^3.0.0",
174    "react-twitter-auth": "0.0.13",
175    "reactstrap": "^8.8.1",
176    "recharts": "^2.0.8",
177    "redux": "^4.0.5",
178    "redux-saga": "^1.1.3",
179    "reselect": "^4.0.0",
180    "sass": "^1.37.5",
181    "simplebar-react": "^2.3.0",
182    "styled": "^1.0.0",
183    "styled-components": "^5.2.1",
184    "toastr": "^2.1.4",
185    "typescript": "^4.0.2",
186    "universal-cookie": "^4.0.4"
187  },
188  "devDependencies": {
189    "@typescript-eslint/eslint-plugin": "^2.27.0",
190    "@typescript-eslint/parser": "^2.27.0",
191    "@typescript-eslint/typescript-estree": "^4.15.2",
192    "eslint-config-prettier": "^6.10.1",
193    "eslint-plugin-prettier": "^3.1.2",
194    "husky": "^4.2.5",
195    "lint-staged": "^10.1.3",
196    "prettier": "^1.19.1",
197    "react-test-renderer": "^16.13.1",
198    "redux-devtools-extension": "^2.13.8",
199    "redux-mock-store": "^1.5.4"
200  },
201  "scripts": {
202    "start": "react-scripts start",
203    "build": "react-scripts build && mv build ./deploy/build",
204    "build-local": "react-scripts build",
205    "test": "react-scripts test",
206    "eject": "react-scripts eject"
207  },
208  "eslintConfig": {
209    "extends": "react-app"
210  },
211  "husky": {
212    "hooks": {
213      "pre-commit": "lint-staged"
214    }
215  },
216  "lint-staged": {
217    "*.{js,ts,tsx}": [
218      "eslint --fix"
219    ]
220  },
221  "browserslist": {
222    "production": [
223      ">0.2%",
224      "not dead",
225      "not op_mini all"
226    ],
227    "development": [
228      "last 1 chrome version",
229      "last 1 firefox version",
230      "last 1 safari version"
231    ]
232  }
233}
234    - name: Fix up git URLs
235      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
236git config --global url."https://github.com/".insteadOf git://github.com/
237git config --global url."git@github.com:".insteadOf git://github.com/
238

That will change any git://github.com/ (unencrypted Git protocol) into git@github.com: (SSH URL).

Source https://stackoverflow.com/questions/70663523

QUESTION

Emulate BTreeMap::pop_last in stable Rust

Asked 2022-Mar-15 at 16:55

In the current stable Rust, is there a way to write a function equivalent to BTreeMap::pop_last?

The best I could come up with is:

1fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
2where
3    K: Ord + Clone,
4{
5    let last = m.iter().next_back();
6    if let Some((k, _)) = last {
7        let k_copy = k.clone();
8        return m.remove_entry(&k_copy);
9    }
10    None
11}
12

It works, but it requires that the key is cloneable. BTreeMap::pop_last from Rust nightly imposes no such constraint.

If I remove the cloning like this

1fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
2where
3    K: Ord + Clone,
4{
5    let last = m.iter().next_back();
6    if let Some((k, _)) = last {
7        let k_copy = k.clone();
8        return m.remove_entry(&k_copy);
9    }
10    None
11}
12fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
13where
14    K: Ord,
15{
16    let last = m.iter().next_back();
17    if let Some((k, _)) = last {
18        return m.remove_entry(k);
19    }
20    None
21}
22

it leads to

1fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
2where
3    K: Ord + Clone,
4{
5    let last = m.iter().next_back();
6    if let Some((k, _)) = last {
7        let k_copy = k.clone();
8        return m.remove_entry(&k_copy);
9    }
10    None
11}
12fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
13where
14    K: Ord,
15{
16    let last = m.iter().next_back();
17    if let Some((k, _)) = last {
18        return m.remove_entry(k);
19    }
20    None
21}
22error[E0502]: cannot borrow `*m` as mutable because it is also borrowed as immutable
23  --> ...
24   |
25.. |     let last = m.iter().next_back();
26   |                -------- immutable borrow occurs here
27.. |     if let Some((k, _)) = last {
28.. |         return m.remove_entry(k);
29   |                ^^------------^^^
30   |                | |
31   |                | immutable borrow later used by call
32   |                mutable borrow occurs here
33

Is there a way to work around this issue without imposing additional constraints on map key and value types?

ANSWER

Answered 2022-Mar-15 at 16:55

Is there a way to work around this issue without imposing additional constraints on map key and value types?

It doesn't appear doable in safe Rust, at least not with reasonable algorithmic complexity. (See Aiden4's answer for a solution that does it by re-building the whole map.)

But if you're allowed to use unsafe, and if you're determined enough that you want to delve into it, this code could do it:

1fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
2where
3    K: Ord + Clone,
4{
5    let last = m.iter().next_back();
6    if let Some((k, _)) = last {
7        let k_copy = k.clone();
8        return m.remove_entry(&k_copy);
9    }
10    None
11}
12fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
13where
14    K: Ord,
15{
16    let last = m.iter().next_back();
17    if let Some((k, _)) = last {
18        return m.remove_entry(k);
19    }
20    None
21}
22error[E0502]: cannot borrow `*m` as mutable because it is also borrowed as immutable
23  --> ...
24   |
25.. |     let last = m.iter().next_back();
26   |                -------- immutable borrow occurs here
27.. |     if let Some((k, _)) = last {
28.. |         return m.remove_entry(k);
29   |                ^^------------^^^
30   |                | |
31   |                | immutable borrow later used by call
32   |                mutable borrow occurs here
33// Safety: if key uses shared interior mutability, the comparison function
34// must not use it. (E.g. it is not allowed to call borrow_mut() on a
35// Rc<RefCell<X>> inside the key). It is extremely unlikely that such a
36// key exists, but it's possible to write it, so this must be marked unsafe.
37unsafe fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
38where
39    K: Ord,
40{
41    // We make a shallow copy of the key in the map, and pass a
42    // reference to the copy to BTreeMap::remove_entry(). Since
43    // remove_entry() is not dropping the key/value pair (it's returning
44    // it), our shallow copy will remain throughout the lifetime of
45    // remove_entry(), even if the key contains references.
46    let (last_key_ref, _) = m.iter().next_back()?;
47    let last_key_copy = ManuallyDrop::new(std::ptr::read(last_key_ref));
48    m.remove_entry(&last_key_copy)
49}
50

Source https://stackoverflow.com/questions/71455966

QUESTION

Error when trying to run my React Native app on Android

Asked 2022-Mar-06 at 07:58

I've built my React Native app and tested and troubleshooted with my iOS devices for months. Now I'm trying to built and test the app on Android for the first time. The thing is, that I keep getting errors trying to run the Android-version of my app. After hours of debugging and troubleshooting, I tried to create a new RN project and see if that could run on my emulator and device. I got that part working and then I wanted to copy/paste the files of my existing app project into the new project.

I pasted my existing assets, styles, the source JS-files and the package.json file into the new project, ran npm install and then I ended up with the exact same error message as I had in the original project when I run react-native run-android.

The full error message is here:

1error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
2Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
3Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
4Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
5Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
6Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
7Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
8
9FAILURE: Build failed with an exception.
10
11* What went wrong:
12Execution failed for task ':app:mergeDebugAssets'.
13> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
14   > Could not find com.facebook.yoga:proguard-annotations:1.14.1.
15     Searched in the following locations:
16       - https://dl.google.com/dl/android/maven2/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
17       - https://repo.maven.apache.org/maven2/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
18       - file:/Users/MyUser/.m2/repository/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
19       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
20       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
21       - https://www.jitpack.io/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
22     Required by:
23         project :app > com.facebook.react:react-native:0.64.2
24   > Could not find com.facebook.fbjni:fbjni-java-only:0.0.3.
25     Searched in the following locations:
26       - https://dl.google.com/dl/android/maven2/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
27       - https://repo.maven.apache.org/maven2/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
28       - file:/Users/MyUser/.m2/repository/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
29       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
30       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
31       - https://www.jitpack.io/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
32     Required by:
33         project :app > com.facebook.react:react-native:0.64.2
34   > Could not find com.yqritc:android-scalablevideoview:1.0.4.
35     Searched in the following locations:
36       - https://dl.google.com/dl/android/maven2/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
37       - https://repo.maven.apache.org/maven2/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
38       - file:/Users/MyUser/.m2/repository/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
39       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
40       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
41       - https://www.jitpack.io/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
42     Required by:
43         project :app > project :react-native-video
44
45* Try:
46Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
47
48* Get more help at https://help.gradle.org
49
50BUILD FAILED in 10s
51
52    at makeError (/Users/MyUser/MyAppFolder/MyApp/node_modules/execa/index.js:174:9)
53    at /Users/MyUser/MyAppFolder/MyApp/node_modules/execa/index.js:278:16
54    at processTicksAndRejections (node:internal/process/task_queues:96:5)
55    at async runOnAllDevices (/Users/MyUser/MyAppFolder/MyApp/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5)
56    at async Command.handleAction (/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/node_modules/@react-native-community/cli/build/index.js:186:9)
57

I've tried to run ./gradlew clean in the android-folder without any luck. My build.gradle-file looks like this:

1error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
2Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
3Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
4Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
5Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
6Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
7Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
8
9FAILURE: Build failed with an exception.
10
11* What went wrong:
12Execution failed for task ':app:mergeDebugAssets'.
13> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
14   > Could not find com.facebook.yoga:proguard-annotations:1.14.1.
15     Searched in the following locations:
16       - https://dl.google.com/dl/android/maven2/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
17       - https://repo.maven.apache.org/maven2/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
18       - file:/Users/MyUser/.m2/repository/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
19       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
20       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
21       - https://www.jitpack.io/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
22     Required by:
23         project :app > com.facebook.react:react-native:0.64.2
24   > Could not find com.facebook.fbjni:fbjni-java-only:0.0.3.
25     Searched in the following locations:
26       - https://dl.google.com/dl/android/maven2/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
27       - https://repo.maven.apache.org/maven2/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
28       - file:/Users/MyUser/.m2/repository/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
29       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
30       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
31       - https://www.jitpack.io/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
32     Required by:
33         project :app > com.facebook.react:react-native:0.64.2
34   > Could not find com.yqritc:android-scalablevideoview:1.0.4.
35     Searched in the following locations:
36       - https://dl.google.com/dl/android/maven2/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
37       - https://repo.maven.apache.org/maven2/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
38       - file:/Users/MyUser/.m2/repository/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
39       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
40       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
41       - https://www.jitpack.io/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
42     Required by:
43         project :app > project :react-native-video
44
45* Try:
46Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
47
48* Get more help at https://help.gradle.org
49
50BUILD FAILED in 10s
51
52    at makeError (/Users/MyUser/MyAppFolder/MyApp/node_modules/execa/index.js:174:9)
53    at /Users/MyUser/MyAppFolder/MyApp/node_modules/execa/index.js:278:16
54    at processTicksAndRejections (node:internal/process/task_queues:96:5)
55    at async runOnAllDevices (/Users/MyUser/MyAppFolder/MyApp/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5)
56    at async Command.handleAction (/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/node_modules/@react-native-community/cli/build/index.js:186:9)
57// Top-level build file where you can add configuration options common to all sub-projects/modules.
58
59buildscript {
60    ext {
61        buildToolsVersion = "30.0.2"
62        minSdkVersion = 21
63        compileSdkVersion = 30
64        targetSdkVersion = 30
65        ndkVersion = "20.1.5948944"
66        kotlinVersion = "1.3.72"
67    }
68    repositories {
69        repositories {
70            google()
71            maven { url 'https://maven.google.com' }
72            mavenLocal()
73            mavenCentral()
74
75           // jcenter()
76            maven {
77                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
78                url "$rootDir/../node_modules/react-native/android"
79            }
80        }
81    }
82    dependencies {
83        classpath("com.android.tools.build:gradle:4.2.1")
84        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
85        // NOTE: Do not place your application dependencies here; they belong
86        // in the individual module build.gradle files
87    }
88}
89
90allprojects {
91    repositories {
92        google()
93        mavenCentral()
94
95        mavenLocal()
96        maven {
97            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
98            url("$rootDir/../node_modules/react-native/android")
99        }
100        maven {
101            // Android JSC is installed from npm
102            url("$rootDir/../node_modules/jsc-android/dist")
103        }
104
105        maven { url 'https://www.jitpack.io' }
106    }
107}
108

Please let me know if you know what to do or if you have experienced a similar issue!

ANSWER

Answered 2021-Aug-21 at 13:43

I've hit this same issue and have temporarily resolved it by uninstalling react-native-video (npm uninstall --save react-native-video). That's not a great answer as I need that component, but I don't have a full solution yet. I think somehow com.yqritc:android-scalablevideoview:1.0.4. is required by react-native-video but has gotten lost or removed. Other thoughts are welcome.

UPDATE: Resolved! In your build.gradle in your Android folder you need to add the repository "jcenter()" in allprojects (not in build dependencies) like this...

1error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
2Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
3Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
4Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
5Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
6Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
7Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
8
9FAILURE: Build failed with an exception.
10
11* What went wrong:
12Execution failed for task ':app:mergeDebugAssets'.
13> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
14   > Could not find com.facebook.yoga:proguard-annotations:1.14.1.
15     Searched in the following locations:
16       - https://dl.google.com/dl/android/maven2/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
17       - https://repo.maven.apache.org/maven2/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
18       - file:/Users/MyUser/.m2/repository/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
19       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
20       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
21       - https://www.jitpack.io/com/facebook/yoga/proguard-annotations/1.14.1/proguard-annotations-1.14.1.pom
22     Required by:
23         project :app > com.facebook.react:react-native:0.64.2
24   > Could not find com.facebook.fbjni:fbjni-java-only:0.0.3.
25     Searched in the following locations:
26       - https://dl.google.com/dl/android/maven2/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
27       - https://repo.maven.apache.org/maven2/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
28       - file:/Users/MyUser/.m2/repository/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
29       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
30       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
31       - https://www.jitpack.io/com/facebook/fbjni/fbjni-java-only/0.0.3/fbjni-java-only-0.0.3.pom
32     Required by:
33         project :app > com.facebook.react:react-native:0.64.2
34   > Could not find com.yqritc:android-scalablevideoview:1.0.4.
35     Searched in the following locations:
36       - https://dl.google.com/dl/android/maven2/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
37       - https://repo.maven.apache.org/maven2/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
38       - file:/Users/MyUser/.m2/repository/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
39       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/android/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
40       - file:/Users/MyUser/MyAppFolder/MyApp/node_modules/jsc-android/dist/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
41       - https://www.jitpack.io/com/yqritc/android-scalablevideoview/1.0.4/android-scalablevideoview-1.0.4.pom
42     Required by:
43         project :app > project :react-native-video
44
45* Try:
46Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
47
48* Get more help at https://help.gradle.org
49
50BUILD FAILED in 10s
51
52    at makeError (/Users/MyUser/MyAppFolder/MyApp/node_modules/execa/index.js:174:9)
53    at /Users/MyUser/MyAppFolder/MyApp/node_modules/execa/index.js:278:16
54    at processTicksAndRejections (node:internal/process/task_queues:96:5)
55    at async runOnAllDevices (/Users/MyUser/MyAppFolder/MyApp/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5)
56    at async Command.handleAction (/Users/MyUser/MyAppFolder/MyApp/node_modules/react-native/node_modules/@react-native-community/cli/build/index.js:186:9)
57// Top-level build file where you can add configuration options common to all sub-projects/modules.
58
59buildscript {
60    ext {
61        buildToolsVersion = "30.0.2"
62        minSdkVersion = 21
63        compileSdkVersion = 30
64        targetSdkVersion = 30
65        ndkVersion = "20.1.5948944"
66        kotlinVersion = "1.3.72"
67    }
68    repositories {
69        repositories {
70            google()
71            maven { url 'https://maven.google.com' }
72            mavenLocal()
73            mavenCentral()
74
75           // jcenter()
76            maven {
77                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
78                url "$rootDir/../node_modules/react-native/android"
79            }
80        }
81    }
82    dependencies {
83        classpath("com.android.tools.build:gradle:4.2.1")
84        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
85        // NOTE: Do not place your application dependencies here; they belong
86        // in the individual module build.gradle files
87    }
88}
89
90allprojects {
91    repositories {
92        google()
93        mavenCentral()
94
95        mavenLocal()
96        maven {
97            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
98            url("$rootDir/../node_modules/react-native/android")
99        }
100        maven {
101            // Android JSC is installed from npm
102            url("$rootDir/../node_modules/jsc-android/dist")
103        }
104
105        maven { url 'https://www.jitpack.io' }
106    }
107}
108allprojects {
109    repositories {
110        mavenCentral()
111        mavenLocal()
112        jcenter()
113}
114

Source https://stackoverflow.com/questions/68835157

QUESTION

throwError(error) is now deprecated, but there is no new Error(HttpErrorResponse)

Asked 2022-Mar-01 at 00:42

Apparently throwError(error) is now deprecated. The IntelliSense of VS Code suggests throwError(() => new Error('error'). new Error(...) accepts only strings. What's the correct way to replace it without breaking my HttpErrorHandlerService ?

http-error.interceptor.ts
1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150
auth.interceptor.ts
1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252

ANSWER

Answered 2021-Aug-04 at 19:08

Instead of this:

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256

You could try this:

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) => {
257      this.authService.signOut();
258      return throwError(() => error);
259    }),
260

I wasn't able to test it thoroughly, but a simple attempt seemed to work.

This was my simple test (using RxJS v7.2):

Service

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) => {
257      this.authService.signOut();
258      return throwError(() => error);
259    }),
260  getProducts(): Observable<IProduct[]> {
261    return this.http.get<IProduct[]>(this.productUrl)
262      .pipe(
263        tap(data => console.log('All: ', JSON.stringify(data))),
264        catchError(this.handleError)
265      );
266  }
267
268  private handleError(err: HttpErrorResponse): Observable<never> {
269    // just a test ... more could would go here
270    return throwError(() => err);
271  }
272

Notice that err here is of type HttpErrorResponse.

Component

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) => {
257      this.authService.signOut();
258      return throwError(() => error);
259    }),
260  getProducts(): Observable<IProduct[]> {
261    return this.http.get<IProduct[]>(this.productUrl)
262      .pipe(
263        tap(data => console.log('All: ', JSON.stringify(data))),
264        catchError(this.handleError)
265      );
266  }
267
268  private handleError(err: HttpErrorResponse): Observable<never> {
269    // just a test ... more could would go here
270    return throwError(() => err);
271  }
272  ngOnInit(): void {
273    this.sub = this.productService.getProducts().subscribe({
274      next: products => {
275        this.products = products;
276        this.filteredProducts = this.products;
277      },
278      error: err => this.errorMessage = err.message
279    });
280  }
281

Here I was able to retrieve the message property from the error response and display it in my UI.

Let me know if this works for you.

Source https://stackoverflow.com/questions/68655492

QUESTION

TypeError: Cannot read properties of undefined (reading 'id')

Asked 2022-Feb-21 at 18:23

I have this error in my terminal:

TypeError: Cannot read properties of undefined (reading 'id')

I'm trying to test the call to an API, but the error appears.

My function:

1itemToForm = () => {
2    this.api.send(this.component, 'get',
3        { lang: 'ES', filter: { id: this.item['id'] } }
4    ).then(resEsp => {
5        this.item = resEsp['data'][0];
6        this.api.send(this.component, 'get',
7            { lang: 'EN', filter: { id: this.item['id'] } }
8        ).then(res => {
9            let itemEng = res['data'][0];
10            let fields = this.formDef.map(register => register.filter(
11                field => field['register_table'].indexOf('traduction') !== -1
12            ).map(
13                field => field['field_name'])
14            ).filter(register => register.length);
15
16            fields = fields.length ? fields[0] : [];
17
18            if (itemEng) {
19                this.item = Object.keys(itemEng).reduce((obj, key) => {
20                    obj[key] = this.item[key];
21                    if (fields.indexOf(key) !== -1) {
22                        obj[key + '_eng'] = itemEng[key];
23                    }
24                    return obj;
25                }, {});
26            }
27
28            if (this.item) {
29                this.setForm();
30            }
31        })
32    })
33}
34

My specification file:

1itemToForm = () => {
2    this.api.send(this.component, 'get',
3        { lang: 'ES', filter: { id: this.item['id'] } }
4    ).then(resEsp => {
5        this.item = resEsp['data'][0];
6        this.api.send(this.component, 'get',
7            { lang: 'EN', filter: { id: this.item['id'] } }
8        ).then(res => {
9            let itemEng = res['data'][0];
10            let fields = this.formDef.map(register => register.filter(
11                field => field['register_table'].indexOf('traduction') !== -1
12            ).map(
13                field => field['field_name'])
14            ).filter(register => register.length);
15
16            fields = fields.length ? fields[0] : [];
17
18            if (itemEng) {
19                this.item = Object.keys(itemEng).reduce((obj, key) => {
20                    obj[key] = this.item[key];
21                    if (fields.indexOf(key) !== -1) {
22                        obj[key + '_eng'] = itemEng[key];
23                    }
24                    return obj;
25                }, {});
26            }
27
28            if (this.item) {
29                this.setForm();
30            }
31        })
32    })
33}
34it('should call api.send', () => {
35    let spy1 = spyOn(api, 'send');
36    let item = {
37        id: 1,
38        name: 'test',
39    }
40
41    component.addItem(item);
42    component.itemToForm();
43
44    expect(spy1).toHaveBeenCalled();
45});
46

ANSWER

Answered 2021-Oct-17 at 15:15

What is happening:

The function itemToForm() is being called before the this.item is ready.

There are many strategies to avoid this error. A very simple one is to add a catcher at the beginning of the function, like this:

1itemToForm = () => {
2    this.api.send(this.component, 'get',
3        { lang: 'ES', filter: { id: this.item['id'] } }
4    ).then(resEsp => {
5        this.item = resEsp['data'][0];
6        this.api.send(this.component, 'get',
7            { lang: 'EN', filter: { id: this.item['id'] } }
8        ).then(res => {
9            let itemEng = res['data'][0];
10            let fields = this.formDef.map(register => register.filter(
11                field => field['register_table'].indexOf('traduction') !== -1
12            ).map(
13                field => field['field_name'])
14            ).filter(register => register.length);
15
16            fields = fields.length ? fields[0] : [];
17
18            if (itemEng) {
19                this.item = Object.keys(itemEng).reduce((obj, key) => {
20                    obj[key] = this.item[key];
21                    if (fields.indexOf(key) !== -1) {
22                        obj[key + '_eng'] = itemEng[key];
23                    }
24                    return obj;
25                }, {});
26            }
27
28            if (this.item) {
29                this.setForm();
30            }
31        })
32    })
33}
34it('should call api.send', () => {
35    let spy1 = spyOn(api, 'send');
36    let item = {
37        id: 1,
38        name: 'test',
39    }
40
41    component.addItem(item);
42    component.itemToForm();
43
44    expect(spy1).toHaveBeenCalled();
45});
46itemToForm = () => {
47  if(this.item === undefined) {return}
48         
49  // The rest of the code
50}
51

This stops the function, if the data does not exist yet.

A more elegant solution may be to go further up in your order of operations, and find who is calling itemToForm() and ensure the data exists prior to calling.

Source https://stackoverflow.com/questions/68959632

QUESTION

What is the proper evaluation order when assigning a value in a map?

Asked 2022-Feb-02 at 09:25

I know that compiler is usually the last thing to blame for bugs in a code, but I do not see any other explanation for the following behaviour of the following C++ code (distilled down from an actual project):

1#include <iostream>
2#include <map>
3
4int main()
5{
6    auto values = { 1, 3, 5 };
7    std::map<int, int> valMap;
8
9    for (auto const & val : values) {
10        std::cout << "before assignment: valMap.size() = " << valMap.size();
11        valMap[val] = valMap.size();
12        std::cout << " -> set valMap[" << val << "] to " << valMap[val] << "\n";
13    }
14}
15

The expected output of this code is:

1#include <iostream>
2#include <map>
3
4int main()
5{
6    auto values = { 1, 3, 5 };
7    std::map<int, int> valMap;
8
9    for (auto const & val : values) {
10        std::cout << "before assignment: valMap.size() = " << valMap.size();
11        valMap[val] = valMap.size();
12        std::cout << " -> set valMap[" << val << "] to " << valMap[val] << "\n";
13    }
14}
15before assignment: valMap.size() = 0 -> set valMap[1] to 0
16before assignment: valMap.size() = 1 -> set valMap[3] to 1
17before assignment: valMap.size() = 2 -> set valMap[5] to 2
18

However, when I build a Release version with the (default) C++14 compiler, the output becomes:

1#include <iostream>
2#include <map>
3
4int main()
5{
6    auto values = { 1, 3, 5 };
7    std::map<int, int> valMap;
8
9    for (auto const & val : values) {
10        std::cout << "before assignment: valMap.size() = " << valMap.size();
11        valMap[val] = valMap.size();
12        std::cout << " -> set valMap[" << val << "] to " << valMap[val] << "\n";
13    }
14}
15before assignment: valMap.size() = 0 -> set valMap[1] to 0
16before assignment: valMap.size() = 1 -> set valMap[3] to 1
17before assignment: valMap.size() = 2 -> set valMap[5] to 2
18before assignment: valMap.size() = 0 -> set valMap[1] to 1
19before assignment: valMap.size() = 1 -> set valMap[3] to 2
20before assignment: valMap.size() = 2 -> set valMap[5] to 3
21

In other words, all values in valMap are larger by 1 than what they should be - it looks like the map gets appended before the right-hand-side of the assignment is evaluated.

This happens only in a Release build with C++14 language standard (which is the default in VS2019). Debug builds work fine (I hate when this happens - it took me hours to find out what is going on), as do Release builds of C++17 and C++20. This is why it looks like a bug to me.

My question is: is this a compiler bug, or am I doing something wrong/dangerous by using .size() in the assignment?

ANSWER

Answered 2022-Feb-01 at 15:49

The evaluation order of A = B was not specified before c++17, after c++17 B is guaranteed to be evaluated before A, see https://en.cppreference.com/w/cpp/language/eval_order rule 20.

The behaviour of valMap[val] = valMap.size(); is therefore unspecified in c++14, you should use:

1#include <iostream>
2#include <map>
3
4int main()
5{
6    auto values = { 1, 3, 5 };
7    std::map<int, int> valMap;
8
9    for (auto const & val : values) {
10        std::cout << "before assignment: valMap.size() = " << valMap.size();
11        valMap[val] = valMap.size();
12        std::cout << " -> set valMap[" << val << "] to " << valMap[val] << "\n";
13    }
14}
15before assignment: valMap.size() = 0 -> set valMap[1] to 0
16before assignment: valMap.size() = 1 -> set valMap[3] to 1
17before assignment: valMap.size() = 2 -> set valMap[5] to 2
18before assignment: valMap.size() = 0 -> set valMap[1] to 1
19before assignment: valMap.size() = 1 -> set valMap[3] to 2
20before assignment: valMap.size() = 2 -> set valMap[5] to 3
21auto size = valMap.size();
22valMap[val] = size;
23

Or avoid the problem by using emplace which is more explicit than relying on [] to automatically insert a value if it doesn't already exist:

1#include <iostream>
2#include <map>
3
4int main()
5{
6    auto values = { 1, 3, 5 };
7    std::map<int, int> valMap;
8
9    for (auto const & val : values) {
10        std::cout << "before assignment: valMap.size() = " << valMap.size();
11        valMap[val] = valMap.size();
12        std::cout << " -> set valMap[" << val << "] to " << valMap[val] << "\n";
13    }
14}
15before assignment: valMap.size() = 0 -> set valMap[1] to 0
16before assignment: valMap.size() = 1 -> set valMap[3] to 1
17before assignment: valMap.size() = 2 -> set valMap[5] to 2
18before assignment: valMap.size() = 0 -> set valMap[1] to 1
19before assignment: valMap.size() = 1 -> set valMap[3] to 2
20before assignment: valMap.size() = 2 -> set valMap[5] to 3
21auto size = valMap.size();
22valMap[val] = size;
23valMap.emplace(val, size);
24

Source https://stackoverflow.com/questions/70943170

QUESTION

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in the package.json of a module in node_modules

Asked 2022-Jan-31 at 17:22

This is a React web app. When I run

1npm start
2

This error occurred

1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6      throw e;
7  ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10    at new NodeError (node:internal/errors:371:5)
11    at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12    at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13    at resolveExports (node:internal/modules/cjs/loader:482:36)
14    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17    at Module.require (node:internal/modules/cjs/loader:999:19)
18    at require (node:internal/modules/cjs/helpers:102:18)
19    at Object.<anonymous> (/Users/juliantc/Desktop/ai-    studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24

This error only occurs when I run this on this specific computer, which I do not have superuser access to. It works on other computers.

For reference, this is ./node_modules/postcss-safe-parser/node_modules/postcss/package.json

1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6      throw e;
7  ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10    at new NodeError (node:internal/errors:371:5)
11    at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12    at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13    at resolveExports (node:internal/modules/cjs/loader:482:36)
14    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17    at Module.require (node:internal/modules/cjs/loader:999:19)
18    at require (node:internal/modules/cjs/helpers:102:18)
19    at Object.<anonymous> (/Users/juliantc/Desktop/ai-    studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25  "name": "postcss",
26  "version": "8.2.6",
27  "description": "Tool for transforming styles with JS plugins",
28  "engines": {
29    "node": "^10 || ^12 || >=14"
30  },
31  "exports": {
32    ".": {
33      "require": "./lib/postcss.js",
34      "import": "./lib/postcss.mjs",
35      "types": "./lib/postcss.d.ts"
36    },
37    "./": "./"
38  },
39  "main": "./lib/postcss.js",
40  "types": "./lib/postcss.d.ts",
41  "keywords": [
42    "css",
43    "postcss",
44    "rework",
45    "preprocessor",
46    "parser",
47    "source map",
48    "transform",
49    "manipulation",
50    "transpiler"
51  ],
52  "funding": {
53    "type": "opencollective",
54    "url": "https://opencollective.com/postcss/"
55  },
56  "author": "Andrey Sitnik <andrey@sitnik.ru>",
57  "license": "MIT",
58  "homepage": "https://postcss.org/",
59  "repository": "postcss/postcss",
60  "dependencies": {
61    "colorette": "^1.2.1",
62    "nanoid": "^3.1.20",
63    "source-map": "^0.6.1"
64  },
65  "browser": {
66    "./lib/terminal-highlight": false,
67    "colorette": false,
68    "fs": false
69  }
70}

And this is what I get when I list the files in ./node_modules/postcss-safe-parser/node_modules/postcss/lib/

lgtd-lt-119-mbmt:frontend juliantc$ ls ./node_modules/postcss-safe-parser/node_modules/postcss/lib/

1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6      throw e;
7  ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10    at new NodeError (node:internal/errors:371:5)
11    at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12    at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13    at resolveExports (node:internal/modules/cjs/loader:482:36)
14    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17    at Module.require (node:internal/modules/cjs/loader:999:19)
18    at require (node:internal/modules/cjs/helpers:102:18)
19    at Object.<anonymous> (/Users/juliantc/Desktop/ai-    studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25  "name": "postcss",
26  "version": "8.2.6",
27  "description": "Tool for transforming styles with JS plugins",
28  "engines": {
29    "node": "^10 || ^12 || >=14"
30  },
31  "exports": {
32    ".": {
33      "require": "./lib/postcss.js",
34      "import": "./lib/postcss.mjs",
35      "types": "./lib/postcss.d.ts"
36    },
37    "./": "./"
38  },
39  "main": "./lib/postcss.js",
40  "types": "./lib/postcss.d.ts",
41  "keywords": [
42    "css",
43    "postcss",
44    "rework",
45    "preprocessor",
46    "parser",
47    "source map",
48    "transform",
49    "manipulation",
50    "transpiler"
51  ],
52  "funding": {
53    "type": "opencollective",
54    "url": "https://opencollective.com/postcss/"
55  },
56  "author": "Andrey Sitnik <andrey@sitnik.ru>",
57  "license": "MIT",
58  "homepage": "https://postcss.org/",
59  "repository": "postcss/postcss",
60  "dependencies": {
61    "colorette": "^1.2.1",
62    "nanoid": "^3.1.20",
63    "source-map": "^0.6.1"
64  },
65  "browser": {
66    "./lib/terminal-highlight": false,
67    "colorette": false,
68    "fs": false
69  }
70}at-rule.d.ts        css-syntax-error.d.ts   input.d.ts      map-generator.js    postcss.d.ts        processor.js        rule.js         tokenize.js
71at-rule.js      css-syntax-error.js input.js        node.d.ts       postcss.js      result.d.ts     stringifier.js      warn-once.js
72comment.d.ts        declaration.d.ts    lazy-result.d.ts    node.js         postcss.mjs     result.js       stringify.d.ts      warning.d.ts
73comment.js      declaration.js      lazy-result.js      parse.d.ts      previous-map.d.ts   root.d.ts       stringify.js        warning.js
74container.d.ts      fromJSON.d.ts       list.d.ts       parse.js        previous-map.js     root.js         symbols.js
75container.js        fromJSON.js     list.js         parser.js       processor.d.ts      rule.d.ts       terminal-highlight.js
76

ANSWER

Answered 2021-Nov-13 at 18:36

I am also stuck with the same problem because I installed the latest version of Node.js (v17.0.1).

Just go for node.js v14.18.1 and remove the latest version just use the stable version v14.18.1

1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6      throw e;
7  ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10    at new NodeError (node:internal/errors:371:5)
11    at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12    at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13    at resolveExports (node:internal/modules/cjs/loader:482:36)
14    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17    at Module.require (node:internal/modules/cjs/loader:999:19)
18    at require (node:internal/modules/cjs/helpers:102:18)
19    at Object.<anonymous> (/Users/juliantc/Desktop/ai-    studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25  "name": "postcss",
26  "version": "8.2.6",
27  "description": "Tool for transforming styles with JS plugins",
28  "engines": {
29    "node": "^10 || ^12 || >=14"
30  },
31  "exports": {
32    ".": {
33      "require": "./lib/postcss.js",
34      "import": "./lib/postcss.mjs",
35      "types": "./lib/postcss.d.ts"
36    },
37    "./": "./"
38  },
39  "main": "./lib/postcss.js",
40  "types": "./lib/postcss.d.ts",
41  "keywords": [
42    "css",
43    "postcss",
44    "rework",
45    "preprocessor",
46    "parser",
47    "source map",
48    "transform",
49    "manipulation",
50    "transpiler"
51  ],
52  "funding": {
53    "type": "opencollective",
54    "url": "https://opencollective.com/postcss/"
55  },
56  "author": "Andrey Sitnik <andrey@sitnik.ru>",
57  "license": "MIT",
58  "homepage": "https://postcss.org/",
59  "repository": "postcss/postcss",
60  "dependencies": {
61    "colorette": "^1.2.1",
62    "nanoid": "^3.1.20",
63    "source-map": "^0.6.1"
64  },
65  "browser": {
66    "./lib/terminal-highlight": false,
67    "colorette": false,
68    "fs": false
69  }
70}at-rule.d.ts        css-syntax-error.d.ts   input.d.ts      map-generator.js    postcss.d.ts        processor.js        rule.js         tokenize.js
71at-rule.js      css-syntax-error.js input.js        node.d.ts       postcss.js      result.d.ts     stringifier.js      warn-once.js
72comment.d.ts        declaration.d.ts    lazy-result.d.ts    node.js         postcss.mjs     result.js       stringify.d.ts      warning.d.ts
73comment.js      declaration.js      lazy-result.js      parse.d.ts      previous-map.d.ts   root.d.ts       stringify.js        warning.js
74container.d.ts      fromJSON.d.ts       list.d.ts       parse.js        previous-map.js     root.js         symbols.js
75container.js        fromJSON.js     list.js         parser.js       processor.d.ts      rule.d.ts       terminal-highlight.js
76nvm uninstall <version>
77

OR

1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6      throw e;
7  ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10    at new NodeError (node:internal/errors:371:5)
11    at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12    at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13    at resolveExports (node:internal/modules/cjs/loader:482:36)
14    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17    at Module.require (node:internal/modules/cjs/loader:999:19)
18    at require (node:internal/modules/cjs/helpers:102:18)
19    at Object.<anonymous> (/Users/juliantc/Desktop/ai-    studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25  "name": "postcss",
26  "version": "8.2.6",
27  "description": "Tool for transforming styles with JS plugins",
28  "engines": {
29    "node": "^10 || ^12 || >=14"
30  },
31  "exports": {
32    ".": {
33      "require": "./lib/postcss.js",
34      "import": "./lib/postcss.mjs",
35      "types": "./lib/postcss.d.ts"
36    },
37    "./": "./"
38  },
39  "main": "./lib/postcss.js",
40  "types": "./lib/postcss.d.ts",
41  "keywords": [
42    "css",
43    "postcss",
44    "rework",
45    "preprocessor",
46    "parser",
47    "source map",
48    "transform",
49    "manipulation",
50    "transpiler"
51  ],
52  "funding": {
53    "type": "opencollective",
54    "url": "https://opencollective.com/postcss/"
55  },
56  "author": "Andrey Sitnik <andrey@sitnik.ru>",
57  "license": "MIT",
58  "homepage": "https://postcss.org/",
59  "repository": "postcss/postcss",
60  "dependencies": {
61    "colorette": "^1.2.1",
62    "nanoid": "^3.1.20",
63    "source-map": "^0.6.1"
64  },
65  "browser": {
66    "./lib/terminal-highlight": false,
67    "colorette": false,
68    "fs": false
69  }
70}at-rule.d.ts        css-syntax-error.d.ts   input.d.ts      map-generator.js    postcss.d.ts        processor.js        rule.js         tokenize.js
71at-rule.js      css-syntax-error.js input.js        node.d.ts       postcss.js      result.d.ts     stringifier.js      warn-once.js
72comment.d.ts        declaration.d.ts    lazy-result.d.ts    node.js         postcss.mjs     result.js       stringify.d.ts      warning.d.ts
73comment.js      declaration.js      lazy-result.js      parse.d.ts      previous-map.d.ts   root.d.ts       stringify.js        warning.js
74container.d.ts      fromJSON.d.ts       list.d.ts       parse.js        previous-map.js     root.js         symbols.js
75container.js        fromJSON.js     list.js         parser.js       processor.d.ts      rule.d.ts       terminal-highlight.js
76nvm uninstall <version>
77nvm uninstall v17.0.1
78

then install the LTS one which is v14.18.1

1npm start
2> dataflow@0.1.0 start
3> react-scripts start
4
5node:internal/modules/cjs/loader:488
6      throw e;
7  ^
8
9Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in /Users/juliantc/Desktop/ai-studio/development/frontend/node_modules/postcss-safe-parser/node_modules/postcss/package.json
10    at new NodeError (node:internal/errors:371:5)
11    at throwExportsNotFound (node:internal/modules/esm/resolve:416:9)
12    at packageExportsResolve (node:internal/modules/esm/resolve:669:3)
13    at resolveExports (node:internal/modules/cjs/loader:482:36)
14    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
15    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
16    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
17    at Module.require (node:internal/modules/cjs/loader:999:19)
18    at require (node:internal/modules/cjs/helpers:102:18)
19    at Object.<anonymous> (/Users/juliantc/Desktop/ai-    studio/development/frontend/node_modules/postcss-safe-parser/lib/safe-parser.js:1:17) {
20  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
21}
22
23Node.js v17.0.1
24{
25  "name": "postcss",
26  "version": "8.2.6",
27  "description": "Tool for transforming styles with JS plugins",
28  "engines": {
29    "node": "^10 || ^12 || >=14"
30  },
31  "exports": {
32    ".": {
33      "require": "./lib/postcss.js",
34      "import": "./lib/postcss.mjs",
35      "types": "./lib/postcss.d.ts"
36    },
37    "./": "./"
38  },
39  "main": "./lib/postcss.js",
40  "types": "./lib/postcss.d.ts",
41  "keywords": [
42    "css",
43    "postcss",
44    "rework",
45    "preprocessor",
46    "parser",
47    "source map",
48    "transform",
49    "manipulation",
50    "transpiler"
51  ],
52  "funding": {
53    "type": "opencollective",
54    "url": "https://opencollective.com/postcss/"
55  },
56  "author": "Andrey Sitnik <andrey@sitnik.ru>",
57  "license": "MIT",
58  "homepage": "https://postcss.org/",
59  "repository": "postcss/postcss",
60  "dependencies": {
61    "colorette": "^1.2.1",
62    "nanoid": "^3.1.20",
63    "source-map": "^0.6.1"
64  },
65  "browser": {
66    "./lib/terminal-highlight": false,
67    "colorette": false,
68    "fs": false
69  }
70}at-rule.d.ts        css-syntax-error.d.ts   input.d.ts      map-generator.js    postcss.d.ts        processor.js        rule.js         tokenize.js
71at-rule.js      css-syntax-error.js input.js        node.d.ts       postcss.js      result.d.ts     stringifier.js      warn-once.js
72comment.d.ts        declaration.d.ts    lazy-result.d.ts    node.js         postcss.mjs     result.js       stringify.d.ts      warning.d.ts
73comment.js      declaration.js      lazy-result.js      parse.d.ts      previous-map.d.ts   root.d.ts       stringify.js        warning.js
74container.d.ts      fromJSON.d.ts       list.d.ts       parse.js        previous-map.js     root.js         symbols.js
75container.js        fromJSON.js     list.js         parser.js       processor.d.ts      rule.d.ts       terminal-highlight.js
76nvm uninstall <version>
77nvm uninstall v17.0.1
78nvm install --lts
79

This worked for me.

Source https://stackoverflow.com/questions/69693907

QUESTION

Build Warning : Mapping new ns to old ns

Asked 2022-Jan-28 at 12:53

So, I'm using Flutter and on running the App, I receive errors like these in the debug console:

1Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
2

I did flutter clean, but no effect.

I tried the answer here: How to change build tools version in Android Studio

But, when I look for build.gradle file, I have two files one in /android and another in /android/app. But both of these do not have any configuration to change buildToolsVersion.

I did sdkmanager --list_installed and I hae two build-tools versions:

1Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
2  build-tools;29.0.2   | 29.0.2  | Android SDK Build-Tools 29.0.2 | build-tools/29.0.2  
3  build-tools;30.0.2   | 30.0.2  | Android SDK Build-Tools 30.0.2 | build-tools/30.0.2  
4

What should I do to fix this Warning ?

Also, I am not using Android Studio. I used this guide to install Flutter without Android Studio: How to Install and Configure Flutter Without Android Studio

ANSWER

Answered 2021-Jul-31 at 19:43

It not happen becuase of you have two build-tools version installed. It happens because of caches so on android studio just invalidating caches and restarting will fix this.

Source https://stackoverflow.com/questions/68600352

QUESTION

Python 3.10 pattern matching (PEP 634) - wildcard in string

Asked 2021-Dec-17 at 10:43

I got a large list of JSON objects that I want to parse depending on the start of one of the keys, and just wildcard the rest. A lot of the keys are similar, like "matchme-foo" and "matchme-bar". There is a builtin wildcard, but it is only used for whole values, kinda like an else.

I might be overlooking something but I can't find a solution anywhere in the proposal:

https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching

Also a bit more about it in PEP-636:

https://www.python.org/dev/peps/pep-0636/#going-to-the-cloud-mappings

My data looks like this:

1data = [{
2          "id"     : "matchme-foo",
3          "message": "hallo this is a message",
4      },{
5          "id"     : "matchme-bar",
6          "message": "goodbye",
7      },{
8          "id"     : "anotherid",
9          "message": "completely diffrent event"
10      }, ...]
11

I want to do something that can match the id without having to make a long list of |'s.

Something like this:

1data = [{
2          "id"     : "matchme-foo",
3          "message": "hallo this is a message",
4      },{
5          "id"     : "matchme-bar",
6          "message": "goodbye",
7      },{
8          "id"     : "anotherid",
9          "message": "completely diffrent event"
10      }, ...]
11for event in data:
12    match event:
13        case {'id':'matchme-*'}: # Match all 'matchme-' no matter what comes next
14            log.INFO(event['message'])
15        case {'id':'anotherid'}:
16            log.ERROR(event['message'])
17

It's a relatively new addition to Python so there aren't many guides on how to use it yet.

ANSWER

Answered 2021-Dec-17 at 10:43

You can use a guard:

1data = [{
2          "id"     : "matchme-foo",
3          "message": "hallo this is a message",
4      },{
5          "id"     : "matchme-bar",
6          "message": "goodbye",
7      },{
8          "id"     : "anotherid",
9          "message": "completely diffrent event"
10      }, ...]
11for event in data:
12    match event:
13        case {'id':'matchme-*'}: # Match all 'matchme-' no matter what comes next
14            log.INFO(event['message'])
15        case {'id':'anotherid'}:
16            log.ERROR(event['message'])
17for event in data:
18    match event:
19        case {'id': x} if x.startswith("matchme"): # guard
20            print(event["message"])
21        case {'id':'anotherid'}:
22            print(event["message"])
23

Quoting from the official documentation,

Guard

We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes on to try the next case block. Note that value capture happens before the guard is evaluated:

1data = [{
2          "id"     : "matchme-foo",
3          "message": "hallo this is a message",
4      },{
5          "id"     : "matchme-bar",
6          "message": "goodbye",
7      },{
8          "id"     : "anotherid",
9          "message": "completely diffrent event"
10      }, ...]
11for event in data:
12    match event:
13        case {'id':'matchme-*'}: # Match all 'matchme-' no matter what comes next
14            log.INFO(event['message'])
15        case {'id':'anotherid'}:
16            log.ERROR(event['message'])
17for event in data:
18    match event:
19        case {'id': x} if x.startswith("matchme"): # guard
20            print(event["message"])
21        case {'id':'anotherid'}:
22            print(event["message"])
23match point:
24     case Point(x, y) if x == y:
25         print(f"The point is located on the diagonal Y=X at {x}.")
26     case Point(x, y):
27         print(f"Point is not on the diagonal.")
28

Source https://stackoverflow.com/questions/70111401

QUESTION

Command CompileSwiftSources failed with a nonzero exit code XCode 13

Asked 2021-Oct-05 at 16:33

I am trying to run a project on the Xcode13, after running a pod cache clean --all, deleting the derived data, and running a pod update. When I clean the project and build it the following error appears:

1CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler (in target 'Alamofire' from project 'Pods')
2    cd /Users/aimoresa/MyProject-iOS/Pods
3    export DEVELOPER_DIR\=/Applications/Xcode.app/Contents/Developer
4    export SDKROOT\=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.0.sdk
5    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc -incremental -module-name Alamofire -Onone -enable-batch-mode -enforce-exclusivity\=checked @/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire.SwiftFileList -DDEBUG -D COCOAPODS -suppress-warnings -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.0.sdk -target x86_64-apple-ios10.0-simulator -g -module-cache-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/ModuleCache.noindex -Xfrontend -serialize-debugging-options -enable-testing -index-store-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Index/DataStore -swift-version 5 -I /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Products/Debug-iphonesimulator/Alamofire -F /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Products/Debug-iphonesimulator/Alamofire -c -j4 -output-file-map /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire-OutputFileMap.json -parseable-output -serialize-diagnostics -emit-dependencies -emit-module -emit-module-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire.swiftmodule -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-generated-files.hmap -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-own-target-headers.hmap -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-all-non-framework-target-headers.hmap -Xcc -ivfsoverlay -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/all-product-headers.yaml -Xcc -iquote -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-project-headers.hmap -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Products/Debug-iphonesimulator/Alamofire/include -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/DerivedSources-normal/x86_64 -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/DerivedSources/x86_64 -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/DerivedSources -Xcc -DPOD_CONFIGURATION_DEBUG\=1 -Xcc -DDEBUG\=1 -Xcc -DCOCOAPODS\=1 -emit-objc-header -emit-objc-header-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire-Swift.h -import-underlying-module -Xcc -ivfsoverlay -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module-overlay.yaml -working-directory /Users/aimoresa/InvestorCentre-iOS/Pods
6
7Command CompileSwiftSources failed with a nonzero exit code
8

ANSWER

Answered 2021-Oct-05 at 16:33

Edited: For people who use Cocoapods, this answer might be useful: https://stackoverflow.com/a/69384358/587609


I also faced this issue, and it seems that there is a known issue on Xcode 13 as mentioned in this document: https://developer.apple.com/documentation/Xcode-Release-Notes/xcode-13-release-notes

Swift libraries depending on Combine may fail to build for targets including armv7 and i386 architectures. (82183186, 82189214)

Workaround: Use an updated version of the library that isn’t impacted (if available) or remove armv7 and i386 support (for example, increase the deployment target of the library to iOS 11 or higher).

If your app is for iOS 11 or higher, one of the libraries should be modified to target iOS 11 or higher (e.g., my app is for iOS 12 or higher).

For example, I am using GRDB.swift, and its minimum iOS version is 10.0. There was a discussion as an issue of this repo, and I followed that comment to solve this issue as follows:

  1. Fork the repository
  2. Change Package.swift to modify the minimum iOS version like:
1CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler (in target 'Alamofire' from project 'Pods')
2    cd /Users/aimoresa/MyProject-iOS/Pods
3    export DEVELOPER_DIR\=/Applications/Xcode.app/Contents/Developer
4    export SDKROOT\=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.0.sdk
5    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc -incremental -module-name Alamofire -Onone -enable-batch-mode -enforce-exclusivity\=checked @/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire.SwiftFileList -DDEBUG -D COCOAPODS -suppress-warnings -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.0.sdk -target x86_64-apple-ios10.0-simulator -g -module-cache-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/ModuleCache.noindex -Xfrontend -serialize-debugging-options -enable-testing -index-store-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Index/DataStore -swift-version 5 -I /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Products/Debug-iphonesimulator/Alamofire -F /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Products/Debug-iphonesimulator/Alamofire -c -j4 -output-file-map /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire-OutputFileMap.json -parseable-output -serialize-diagnostics -emit-dependencies -emit-module -emit-module-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire.swiftmodule -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-generated-files.hmap -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-own-target-headers.hmap -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-all-non-framework-target-headers.hmap -Xcc -ivfsoverlay -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/all-product-headers.yaml -Xcc -iquote -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Alamofire-project-headers.hmap -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Products/Debug-iphonesimulator/Alamofire/include -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/DerivedSources-normal/x86_64 -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/DerivedSources/x86_64 -Xcc -I/Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/DerivedSources -Xcc -DPOD_CONFIGURATION_DEBUG\=1 -Xcc -DDEBUG\=1 -Xcc -DCOCOAPODS\=1 -emit-objc-header -emit-objc-header-path /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/Objects-normal/x86_64/Alamofire-Swift.h -import-underlying-module -Xcc -ivfsoverlay -Xcc /Users/aimoresa/Library/Developer/Xcode/DerivedData/LinkProject-bwzldrnlucfenpavteypbjybxdky/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Alamofire.build/unextended-module-overlay.yaml -working-directory /Users/aimoresa/InvestorCentre-iOS/Pods
6
7Command CompileSwiftSources failed with a nonzero exit code
8let package = Package(
9name: "GRDB",
10platforms: [
11    .iOS("12.0"),   // changed here
12    .macOS("10.10"),
13    .tvOS("9.0"),
14    .watchOS("2.0"),
15],
16...
17
  1. Modify Podfile or Swift Package Manager (SPM) config to use my forked repository

I am using five libraries via SPM in my Xcode project, but applying the above method to only one of those libraries solved this issue.

There is also a related thread in the Apple forum: https://developer.apple.com/forums/thread/682285

Source https://stackoverflow.com/questions/69276367

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Map

Tutorials and Learning Resources are not available at this moment for Map

Share this Page

share link

Get latest updates on Map