Get cookie by subdomain wise in react js using universal-cookie

I am using universal-cookie in my React JS project to store a token. I am setting cookies for both the domain and subdomain. My domain is testdomain.com and my subdomain is demo.subdomain.com. When I set the cookie for the domain and try to access it from the subdomain, I am getting the domain cookie instead of the subdomain cookie.

Here is the my function to set the cookie

export const setCookies = (key: string, value: string) => {
  const cookies = new Cookies();
  const currentDate = moment();
  const newDate = currentDate.add(2, "days").toDate();
  cookies.set(key, value, {
    path: "/",
    expires: newDate,
    secure: true,
  });
};

In the component, I am accessing the cookie using getCookies function

export const getCookies = (key: string) => {
  const cookies = new Cookies();
  return cookies.get(key);
};

Here I want to specify the cookie by subdomain. In the cookie it is already stored for both i.e. for subdomain and domain.

I have used same key name.

Unable to run haunted.js application

Im trying to run locally this starter app:

https://github.com/matthewp/haunted-starter-app

But I dont seem to have any luck.
After running

npm install

Then I want to run the application. But how? How am I supposed to run it? In package.json there are no references to any library to start the browser and run the app.
So what if I try to open the web broser and the file? Well it fails, which makes sense. I got cors issue:

Access to script at 'file://src/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: chrome, chrome-extension, chrome-untrusted, data, http, https, isolated-app.       

I would have expected starter repo should also include stuff to make it run.

Issue with Redirecting to Login Page After Successful Login in Nuxt.js from Laravel Api

I’m working on a project in Nuxt.js adn Laravel api and I’ve encountered an issue with redirecting users after a successful login. After logging in, the user is redirected immediately to the dashboard (/dashboard), which works as expected. However, if the user then manually enters the home page URL (http://localhost:3000), they are briefly redirected to the login page (/) for about a second before the middleware fetches the user data and redirects them back to the dashboard. This flicker looks very unprofessional and confusing for users.

Middleware Code
Here’s a simplified version of my authentication middleware:

export default defineNuxtRouteMiddleware(async (to, from) => {
    const { me, user } = useAuth();

    try {
        await me(); 
        if (!user.value) {
            return navigateTo('/'); 
        }
    } catch (error) {
        console.error("Error loading user data:", error);
        return navigateTo('/'); 
    }
});

And my guest middleware:

export default defineNuxtRouteMiddleware(async (to, from) => {
    const { me, user } = useAuth();

    if (!user.value) {
        try {
            await me(); 
        } catch (error) {
            console.error("Error loading user data:", error);
        }
    }

    if (user.value) {
        return navigateTo('/dashboard'); 
    }
});

This is my useAuth.js

export default function useAuth() {
    const user = useState('auth-user', () => null)

    const { errorBag, transformValidationErrors, resetErrorBag } = useCustomError()

    const { api, csrf } = useAxios()

    async function me() {
        try {
            const data = await api.get("/api/me")
            user.value = data.data
        } catch (e) {
            user.value = null
            console.log("error")
        }
    }

    function login(userForm) {
        resetErrorBag();
        csrf().then(() => {
            api.post("/login", userForm)
            .then(({ data }) => {
                user.value = data.user;
    
                $fetch('/api/set-cookie', {
                    method: "POST",
                    body: { token: data.token }
                }).then(res => {
                    navigateTo("/dashboard");
                });
            })
            .catch(err => {
                // Don't set the user or token on error
                user.value = null;
                transformValidationErrors(err.response);
            });
        });
    }


    function logout() {
        api.post("/api/logout").then(() => {
            user.value = null
            $fetch('/api/logout', {
                method: "POST",
            }).then(res => {
                navigateTo("/")
            })

        })
    }

    function register(userForm) {

        resetErrorBag()
        csrf().then(() => {
            api.post("/register", userForm).then(({ data }) => {
                //   verify email screen
            }).catch(err => {
                transformValidationErrors(err.response)
            })
        })
    }

    function forgotPassword(userForm){
        resetErrorBag()
        
        csrf().then(() => {

            api.post('/forgot-password', userForm).then(({data}) => {
                alert("Odkaz na obnovení hesla byl úspěšně odeslán na váš email.");
            }).catch(err => {
                transformValidationErrors(err.response)
            })
        })

    }

    function resetPassword(userForm){
        resetErrorBag()
            api.post('/reset-password', userForm).then(res => {
                console.log(res);
                navigateTo("/")
            }).catch(err => {
                transformValidationErrors(err.response)
            })
    }

    return { login, logout, register, errorBag, user, me, forgotPassword, resetPassword }

}

In some way, I simply need to maintain the authenticated user state throughout the entire process, but I am struggling to achieve that

The Role of Indigenous Institutions in Conflict Transformation and Peacemaking: The Case of East Hararge Zone, Oromia Regional State, Ethiopia [closed]

My problem is there is no get any related document or proposal and also i cant designe Statement of The problem and Research Question Part Litrechere Review part the write me all of the above by APA 7 citation and reference around 54 page My name is Abadir Youya musa I learning at Haramaya universty colleage of social Sicence and Humanities

introduction full partes around page 4

LM LIMON Islam rohoman

How do I adjust Islamic hijri date using moment-hijri.js? I’m using this calendar and added moment-hijri.js to add Islamic hijri date. However, I want to give the users the option to change/modify/adjust the date. If I add the following line to drawDay function, the webpage …

How to send push notifications or keep WebSocket active when a browser tab becomes inactive or snoozed in Vue.js?

I have a web dashboard built using Vue.js that relies on WebSockets (Pusher) to receive orders in real-time. When an order is received, a sound plays to notify the user. Everything works fine when the tab is active, but as soon as the browser tab becomes inactive or snoozed, the WebSocket connection seems to stop receiving data, and the sound notification doesn’t play until the tab is revisited.

What I’ve tried:

I’ve tried implementing a Web Worker to keep the WebSocket connection alive, but it doesn’t seem to work when the tab is snoozed.
I also explored using service workers, but I’m not sure how to make them interact with WebSocket and play sound on the page.

What I need:

Is there any way to achieve the following:

  • Keep receiving WebSocket data (or simulate it) when the tab becomes
    inactive or snoozed.
  • Send a push notification to the user’s browser (outside the web page)
    when a new order arrives, so the user can be notified and return
    to the tab.
  • Play a sound or show some visual notification when an order is
    received, even if the tab is not active.

Any suggestions or best practices for handling WebSocket communication and notifications while the tab is snoozed would be greatly appreciated!

Node.js: Date math in a particular time zone

I’d like to find the time offset to a particular time (let’s say 9:30am) on a particular date in Pacific Time, whereas my program may be running in some other locale. This won’t work:

const targetdate = '12/13/2025';
const target = new Date(targetdate);
target.setHours(9, 30);  // won't work, uses local time zone
const timeDelta = target - new Date();

because setHours uses the local time zone rather than Pacific.

The following won’t work half the year either:

const PST_offset = 7;  // won't work if target date is DST
target.setUTCHours(9 + PST_offset, 30);  

because the offset from UTC is different during daylight savings time.

I’m not sure how to go about this. Is there some way to tell Node to use Pacific as its locale? I’m aware of Intl.DateTimeFormat too but that has to do with displaying dates & times, not Date math.

Error with connecting to crossbar from JavaScript

I hope someone can help with this:
We have crossbar running as the backend, and on the client side, we have this code in JavaScript:

connection.onclose = function(reason, details) {
    if(details && details.reason === "loggedOut") {
        appEvents.trigger("sessionExpired");
        return false;
    }
    else {
        console.log(`Crossbar connection closed because of ${reason}. Attempting to reconnect in ${RETRY_DELAY_SECONDS} seconds.`);
        if(details) {
            console.log(`Details of closed connection: `, details.message);
        }
        else {
            console.log("No details found");
        }
    }
}

When it is running we got the error:

Crossbar connection closed because of closed. Attempting to reconnect in 5 seconds
Details of closed connection:  got invalid return type "<class 'NoneType'>" from dynamic authenticator

I tried to reference the error with crossbar Python code, I and I found
in crossbar/router/auth/pending.py

   def _assign_principal(self, principal):
        if isinstance(principal, str):
            # FIXME: more strict authrole checking
            pass
        elif isinstance(principal, dict):
            # FIXME: check principal
            pass
        else:
            error = ApplicationError.AUTHENTICATION_FAILED
            message = 'got invalid return type "{}" from dynamic authenticator'.format(type(principalsp))

So it might be some sort of authentication failed here, but I have no glue what I have to modify the crossbar settings to make the connection work.
Could someone help me to explain this, thank you very much

AppSync util method converts filter to non valid condition object

I want to grab the results using my sort key (resource_id) and a property defining the user’s workspace id. But I run into the following error message every time: “code.js:15:12: Property ‘filter’ is expected to be a valid condition object”

Without the filter the scan resolves and returns results. So I confirmed something is wrong with my filter object. I checked and it’s like how the docs implemented it

I have the following query:

query MyQuery {
  listAuditLog(limit: 2, filter: {resource_id: {eq: "AUDITLOG"}, workspace: {eq: "WORKSPACE-123"}}) {
    nextToken
    items {
      workspace
      users
      created
    }
  }
}

My code for my resolver

import * as ddb from '@aws-appsync/utils/dynamodb'
import { util } from '@aws-appsync/utils'

/**
 * Queries a DynamoDB table, limits the number of returned items, and paginates with the provided `nextToken`
 * @param {import('@aws-appsync/utils').Context<{filter?: any; limit?: number; nextToken?: string}>} ctx the context
 * @returns {import('@aws-appsync/utils').DynamoDBScanRequest} the request
 */
export function request(ctx) {
    const { limit, nextToken } = ctx.args;
    const filter = util.transform.toDynamoDBFilterExpression(ctx.args.filter);
    
    return ddb.scan({
        filter: JSON.parse(filter),
        limit: limit || 20,
        nextToken,
    });
}

/**
 * Returns the query items
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {{items: any[]; nextToken?: string}} the result
 */
export function response(ctx) {
    const { error, result } = ctx;
    if (error) {
        util.error(ctx.error.message, ctx.error.type);
    }
    const { items = [], nextToken } = result;
    return { items, nextToken };
}

Right before the ddb.scan method the filter object looks like this:

{
    "expression": "(#resource_id = :resource_id_eq) AND (#workspace = :workspace_eq)",
    "expressionNames": {
        "#workspace": "workspace",
        "#resource_id": "resource_id"
    },
    "expressionValues": {
        ":resource_id_eq": {
            "S": "AUDITLOG"
        },
        ":workspace_eq": {
            "S": "WORKSPACE-123"
        }
    }
}

Newer to AWS AppSync so I’m probably overlooking something but I read the docs over and over and idk what’s going on. Another set of eyes may help though.

Sending the wrong value to the controller with Url.Action

I want to call an action in the controller in the view and I have to send a series of values ​​to the controller, but the action calls the controller but sends null values. please help me

enter image description here

Code in view:

var _getDocumentsUrl = '@Html.Raw(@Url.Action("GetDocuments", "Document", new { Section = "0", Province = "1", County = "0", District = "0", area = "Province" }))';

Action in Controller:

public IActionResult GetDocuments(AreaVM area)
{///codes////}

Model:

public class AreaVM
{
    public string? Section {  get; set; }
    public string? Province {  get; set; }
    public string? County {  get; set; }
    public string? District {  get; set; }
}

Sending the values ​​of section = 0, Province = 1, County = 0, and District = 0 to the controller

Why is my token rotation not working with auth.js in nextjs 14

I am trying to create a project with nextjs 14 app router. In my project I have used next-auth(5) or auth.js for authentication and authorization. So everything works fine with auth.js but facing a problem with access token expiry time. Though auth.js handle our authentication and authorization for each request .But I want to customize only for credentials. I have set two types (access token and refresh token) of tokens for authentication.In access token I have set access token expiry time 20 seconds. But after successfull login in jwt callbacks access token expiry time set with default expiry time (30 days). So how can I customize the access token expiry value in jwt callbacks? Below I provide the files responsible with authentication and authorization..

auth.js file

    import bcrypt from "bcryptjs";
    import NextAuth, { AuthError } from "next-auth";
    import CredentialsProvider from "next-auth/providers/credentials";
    import FacebookProvider from "next-auth/providers/facebook";
    import GoogleProvider from "next-auth/providers/google";
    import { authConfig } from "./auth.config";
    import { User } from "./models/user-model";
    
    import { getNewTokens } from "./lib/getNewTokens";
    import { refreshAccessToken } from "./lib/refreshAccessToken";
    
    class customError extends AuthError {
      constructor(message) {
        super();
        this.message = message;
      }
    }
    
    export const {
      handlers: { GET, POST },
      auth,
      signIn,
      signOut,
    } = NextAuth({
      ...authConfig,
      providers: [
        CredentialsProvider({
          async authorize(credentials) {
            if (!credentials) return null;
    
            try {
              // Find the user based on the email provided
              const user = await User.findOne({ email: credentials.email }).lean();
              if (!user) {
                console.error("User not found");
                throw new Error("Invalid email or password");
              }
    
              // Compare the entered password with the stored password hash
              const isPasswordMatch = await bcrypt.compare(
                credentials.password,
                user?.password
              );
              if (!isPasswordMatch) {
                console.error("Password mismatch");
                throw new Error("Invalid email or password");
              }
    
              // Return the user object if authentication is successful
              return user;
            } catch (error) {
              // Log and throw the error to be caught in the calling function
              throw new customError(error.message);
            }
          },
        }),
        GoogleProvider({
          clientId: process.env.GOOGLE_CLIENT_ID,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET,
          authorization: {
            params: {
              prompt: "consent",
              access_type: "offline",
              response_type: "code",
            },
          },
        }),
        FacebookProvider({
          clientId: process.env.FACEBOOK_CLIENT_ID,
          clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
        }),
      ],
      trustHost:
        process.env.NODE_ENV === "production" ? true : ["localhost", "127.0.0.1"],
    
      callbacks: {
        async signIn({ user, account, profile }) {
          if (account.provider === "google" || account.provider === "facebook") {
            try {
              const existingUser = await User.findOne({ email: user.email });
              if (!existingUser) {
                const newUser = new User({
                  email: user.email,
                  name: user.name,
                  password: "sample password",
                  role: "customer",
                });
                await newUser.save();
              }
              return true;
            } catch (error) {
              console.error("Error saving user to the database:", error);
              return false;
            }
          }
          return true;
        },
    
        async jwt({ token, user, account }) {
          const currentTime = Math.floor(Date.now() / 1000);
          const accessTokenExpirationTime = 20;
          const refreshTokenExpirationTime = 3600;
          // First time logging in (account and user exist)
          if (user && account) {
            console.log({ user, account, tokenInsideJWT: token });
            // For credentials login
            if (account.provider === "credentials") {
              const newToken = await getNewTokens({
                userId: user.id || user._id.toString(),
                name: user.firstName + user.lastName,
                email: user.email,
              });
    
              return {
                ...token,
                accessToken: newToken?.accessToken,
                refreshToken: newToken?.refreshToken,
                iat: currentTime,
                exp: currentTime + accessTokenExpirationTime,
                refreshTokenExpires: currentTime + refreshTokenExpirationTime,
                provider: account.provider,
                user,
              };
            }
    
            // For social login (Google, Facebook, etc.)
            return {
              ...token,
              accessToken: account.access_token,
              refreshToken: account.refresh_token,
              iat: currentTime,
              exp: currentTime + accessTokenExpirationTime,
              refreshTokenExpires: currentTime + refreshTokenExpirationTime,
              provider: account.provider,
              user,
            };
          }
    
          // Token refresh: Check if the access token has expired
          if (Date.now() / 1000 > token.exp) {
            const refreshedToken = await refreshAccessToken(token);
            console.log(
              "Access token has expired, refreshedTokens...",
              refreshedToken
            );
            return {
              ...refreshedToken,
              exp: currentTime + accessTokenExpirationTime,
              refreshTokenExpires: currentTime + refreshTokenExpirationTime,
            };
          }
    
          console.log({ token }); // **Here I got the default value (30 days) of access token expiry time**
    
          // If the token is valid, ensure the custom expiration is maintained
          // Here we explicitly ensure that the exp is updated every time, even if the token already exists
          if (token && token?.exp) {
            return {
              ...token,
              exp: currentTime + accessTokenExpirationTime, // Force the 20-second expiration on   each call
            };
          }
    
          return token;
        },
    
        async session({ session, token }) {
          console.log({ token }); // **Here I got the customize value (20 sec) of access token expiry time**
          const date = new Date(token?.exp * 1000);
          const options = {
            timeZone: "Asia/Dhaka",
            year: "numeric",
            month: "long",
            day: "numeric",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
          };
    
          if (token) {
            session.user = token?.user;
            session.accessToken = token?.accessToken;
            session.error = token?.error;
            session.expires = new Intl.DateTimeFormat("en-US", options).format(
              date
            );
          }
    
          return session;
        },
      },
    });
    

if access token expired within 20 seconds I want to regenrate access token as well as refresh token. For this I have created a refreshAccessToken function and this works perfectly…..

    export async function refreshAccessToken(token) {
      let url = null;
      if (token?.provider === "credentials") {
        url =
          `http://localhost:3000/api/auth/refreshToken?` +
          new URLSearchParams({
            grant_type: "refresh_token",
            refresh_token: token?.refreshToken,
          });
      }
    
      if (token?.provider === "google") {
        url =
          `https://oauth2.googleapis.com/token?` +
          new URLSearchParams({
            client_id: process.env.GOOGLE_CLIENT_ID,
            client_secret: process.env.GOOGLE_CLIENT_SECRET,
            grant_type: "refresh_token",
            refresh_token: token?.refreshToken,
          });
      }
    
      try {
        const response = await fetch(url, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          method: "POST",
        });
        const refreshedTokens = await response.json();
    
        if (response?.status !== 200 || !response.ok) {
          throw refreshedTokens;
        }
    
        console.log({ refreshedTokensInsideRefresh: refreshedTokens });
        return {
          ...token,
          accessToken:
            refreshedTokens?.accessToken || refreshedTokens?.access_token,
          refreshToken:
            refreshedTokens?.refreshToken || refreshedTokens?.refreshToken,
        };
      } catch (error) {
        console.log(error);
        return {
          ...token,
          error: "RefreshAccessTokenError",
        };
      }
    }

this function responsible for creating new tokens….

    import { SignJWT } from "jose";
    
    // Function to generate tokens
    export const getNewTokens = async (user) => {
      const secretKey = new TextEncoder().encode(process.env.AUTH_SECRET);
    
      const currentDate = new Date().toLocaleString("en-US", {
        timeZone: "Asia/Dhaka",
      });
      const timestamp = new Date(currentDate).getTime();
      const nowInSeconds = Math.floor(timestamp / 1000);
    
      const payload = {
        id: user.userId,
        email: user.email,
        name: user.name,
      };
    
      // Access token (expires in 1 hour)
      const accessToken = await new SignJWT({ ...payload, type: "access" })
        .setProtectedHeader({ alg: "HS256" })
        .setIssuedAt(nowInSeconds)
        .setExpirationTime("20s") // 1 hour from now
        .sign(secretKey);
    
      // Refresh token (expires in 1 day)
      const refreshToken = await new SignJWT({ ...payload, type: "refresh" })
        .setProtectedHeader({ alg: "HS256" })
        .setIssuedAt(nowInSeconds)
        .setExpirationTime("1h") // 1 day from now
        .sign(secretKey);
    
      return { accessToken, refreshToken };
    };
    


I want to customize the default token of auth.js and set expiry time for each of tokens (access token and refresh token)

javsacript react pagination when 5 columns data in a row

I tired to show five blocks in the ui view. on click of next button next five data should display and hide first 5 data block like that click on next button ,display next set of 5. my code here using javscript/react

.parent{
    display: flex;
}

.child{
    margin: 2% 0 0 0;
    width: 33%;
}

 <div className="parent"  >
              {list &&  
              list.data.map((item, index) => (
                <div key={index} className="child">
                  {item.name}
                </div>
            ))}
           </div>

enter image description here

why does live server injection code is showing in my webpage that am working on , it’s litearly showing what’s inside the script?

// <![CDATA[ <-- For SVG support if ('WebSocket' in window) { (function () { function refreshCSS() { var sheets = [].slice.call(document.getElementsByTagName("link")); var head = document.getElementsByTagName("head")[0]; for (var i = 0; i < sheets.length; ++i) { var elem = sheets[i]; var parent = elem.parentElement || head; parent.removeChild(elem); var rel = elem.rel; if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") { var url = elem.href.replace(/(&|?)_cacheOverride=d+/, ''); elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf()); } parent.appendChild(elem); } } var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://'; var address = protocol + window.location.host + window.location.pathname + '/ws'; var socket = new WebSocket(address); socket.onmessage = function (msg) { if (msg.data == 'reload') window.location.reload(); else if (msg.data == 'refreshcss') refreshCSS(); }; if (sessionStorage && !sessionStorage.getItem('IsThisFirstTime_Log_From_LiveServer')) { console.log('Live reload enabled.'); sessionStorage.setItem('IsThisFirstTime_Log_From_LiveServer', true); } })(); } else { console.error('Upgrade your browser. This Browser is NOT supported WebSocket for Live-Reloading.'); } // ]]> 

just like that i find at the end of the webpage just like where it’s being injected

am just expecting the code to not show up

Can I use a loader out of a route?

I’m using React Router’s loader to “send” the loaded data to a component via its route in the App.jsx component, like this

<Route 
  path="vans" 
  element={<HostVans />}
  errorElement={<Error />} 
  loader={hostVansLoader} 
/>

This way, I can load the vans data before the HostVans.jsx component loads, instead of using useEffect to fetch the vans data while the component loads.

Then, in the HostVans.jsx component, I’m receiving the data using useLoaderData, like this:

import { useSearchParams, useLoaderData } from "react-router-dom"

...

const vans = useLoaderData();

However, in different place in my app, I’m also using the HostVans.jsx component as a nested / child component to another parent component, and that means the HostVans.jsx component isn’t loaded via route but just called inside the Dashboard.jsx component, like this:

<div className="container dashboard-container">
  ... 
  <section className="row reviews-section">
    <div className="col-10">
      <h2 className="reviews-heading">Review score</h2>
      <FaStar className="reviews-icon"/>
      <p className="review-score">5.0<span>/5</span></p>
    </div>
    <div className="col-2">
      <Link to="#">Details</Link>
    </div>
  </section>
 </div>
 <HostVans />

Is there any way I can “send” the vans data via the loader when there’s no routing involved (when the component is called inside another component)?

I tried this, but it’s not working:

<HostVans loader={hostVansLoader} />

In other words, the HostVans.jsx component is coded so that it’s expecting the loader data, but when called from Dashboard.jsx (no routing involved), the data is not being sent. How can I solve it?

How to add several custom fields (buttons) in strapi

I’m trying to add another button to the existing one in strapi, but it throws an error (it just doesn’t load entities into the content-manager). What could be causing the problem?
If you give the buttons the same name, pluginid and plugin, then the second button will simply repeat the actions of the first

plugins/custom-button/index.ts

register({ strapi }) {
    strapi.customFields.register({
      name: "custom-button-source",
      plugin: "custom-button",
      type: "string",
    },
    {
      name: "custom-button-article",
      plugin: "custom-button",
      type: "string"
    });
  }

src/plugins/custom-button/admin/src/pluginId.js

import pluginPkg from '../../package.json';

const pluginId = pluginPkg.name.replace(/^(@[^-,.][w,-]+/|strapi-)plugin-/i, '');

export default pluginId;

custom-plugin part in package.json

"name": "custom-button",
  "version": "0.0.0",
  "description": "This is the description of the plugin.",
  "strapi": {
    "name": "custom-button",
    "description": "Description of Custom Button plugin",
    "kind": "plugin",
    "displayName": "Custom Button"

getTrad.js

import pluginId from '../pluginId';

const getTrad = (id) => `${pluginId}.${id}`;

export default getTrad;

plugins/custom-button/admin/src/index.js

import { prefixPluginTranslations } from "@strapi/helper-plugin";
import pluginPkg from "../../package.json";
import pluginId from "./pluginId";
import Initializer from "./components/Initializer";
import PluginIcon from "./components/PluginIcon";

const name = pluginPkg.strapi.name;

const getTrad = (id) => `${pluginId}.${id}`;

export default {
  register(app) {
    app.registerPlugin({
      id: pluginId,
      initializer: Initializer,
      name: "custom-button-source",
      icon: PluginIcon,
      isReady: true,
      isRequired: false,
      translations: {},
    });

    app.registerPlugin({
      id: pluginId,
      initializer: Initializer,
      name: "custom-button-article",
      icon: PluginIcon,
      isReady: true,
      isRequired: false,
      translations: {},
    });

    app.customFields.register({
      name: "custom-button-source",
      pluginId: pluginId,
      type: "string",
      intlLabel: {
        id: getTrad("custom-button.label"),
        defaultMessage: "Variants",
      },
      intlDescription: {
        id: getTrad("custom-button.description"),
        defaultMessage: "Variants (Cartesian product)",
      },
      icon: PluginIcon,
      components: {
        Input: async () =>
          import(
            /* webpackChunkName: "input-component" */ "./components/CustomSourceButton"
          ),
      },
      options: {},
    });

    app.customFields.register({
      name: "custom-button-article",
      pluginId: pluginId,
      type: "string",
      intlLabel: {
        id: getTrad("custom-button.label"),
        defaultMessage: "Articles",
      },
      intlDescription: {
        id: getTrad("custom-button.description"),
        defaultMessage: "Articles (Cartesian product)",
      },
      icon: PluginIcon,
      components: {
        Input: async () =>
          import(
            /* webpackChunkName: "input-component" */ "./components/CustomArticleButton"
          ),
      },
      options: {},
    });
  },


  bootstrap(app) {},
  async registerTrads({ locales }) {
    const importedTrads = await Promise.all(
      locales.map((locale) => {
        return import(`./translations/${locale}.json`)
          .then(({ default: data }) => {
            return {
              data: prefixPluginTranslations(data, pluginId),
              locale,
            };
          })
          .catch(() => {
            return {
              data: {},
              locale,
            };
          });
      })
    );

    return Promise.resolve(importedTrads);
  },
};