@wix/astro 0.3.4 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/build/index.d.ts +5 -0
  2. package/build/index.js +124854 -0
  3. package/build/index.js.map +1 -0
  4. package/build/xdg-open +1267 -0
  5. package/build/yoga.wasm +0 -0
  6. package/build-runtime/auth.d.ts +5 -0
  7. package/build-runtime/auth.js +3557 -0
  8. package/package.json +37 -47
  9. package/runtime/entry.astro +26 -0
  10. package/src/directories.ts +10 -0
  11. package/src/env.d.ts +3 -0
  12. package/src/index.ts +217 -0
  13. package/src/middleware/auth.ts +115 -0
  14. package/src/plugins/patchGlobal.ts +20 -0
  15. package/src/utils/authStrategyAsyncLocalStorage.ts +6 -0
  16. package/src/utils/createProjectModel.ts +77 -0
  17. package/src/utils/generateAppManifest.ts +32 -0
  18. package/src/utils/isValidBackofficeComponent.ts +15 -0
  19. package/src/utils/loadExtension.ts +59 -0
  20. package/src/utils/sessionCookieJson.ts +9 -0
  21. package/src/utils/writeVirtualExtensionFiles.ts +54 -0
  22. package/tsconfig.json +8 -0
  23. package/tsup.config.mjs +28 -0
  24. package/README.md +0 -121
  25. package/dist/auth-context.d.ts +0 -5
  26. package/dist/auth-context.js +0 -2
  27. package/dist/client.d.ts +0 -15
  28. package/dist/client.js +0 -16
  29. package/dist/components/login-helpers/bi-header-generator.d.ts +0 -11
  30. package/dist/components/login-helpers/bi-header-generator.js +0 -17
  31. package/dist/components/login-helpers/iframeUtils.d.ts +0 -4
  32. package/dist/components/login-helpers/iframeUtils.js +0 -43
  33. package/dist/components/login-helpers/login-helpers.d.ts +0 -42
  34. package/dist/components/login-helpers/login-helpers.js +0 -119
  35. package/dist/components/login.astro +0 -872
  36. package/dist/entrypoints/server.d.ts +0 -13
  37. package/dist/entrypoints/server.js +0 -36
  38. package/dist/helpers/index.d.ts +0 -1
  39. package/dist/helpers/index.js +0 -1
  40. package/dist/index.d.ts +0 -5
  41. package/dist/index.js +0 -4
  42. package/dist/integration.d.ts +0 -22
  43. package/dist/integration.js +0 -233
  44. package/dist/loaders/blog.d.ts +0 -2
  45. package/dist/loaders/blog.js +0 -48
  46. package/dist/loaders/index.d.ts +0 -2
  47. package/dist/loaders/index.js +0 -2
  48. package/dist/middleware.d.ts +0 -2
  49. package/dist/middleware.js +0 -89
  50. package/dist/routes/auth/callback.d.ts +0 -3
  51. package/dist/routes/auth/callback.js +0 -52
  52. package/dist/routes/auth/constants.d.ts +0 -5
  53. package/dist/routes/auth/constants.js +0 -5
  54. package/dist/routes/auth/login.d.ts +0 -3
  55. package/dist/routes/auth/login.js +0 -26
  56. package/dist/routes/auth/logout-callback.d.ts +0 -3
  57. package/dist/routes/auth/logout-callback.js +0 -9
  58. package/dist/routes/auth/logout.d.ts +0 -3
  59. package/dist/routes/auth/logout.js +0 -10
  60. package/dist/routes/auth/runtime.d.ts +0 -5
  61. package/dist/routes/auth/runtime.js +0 -7
  62. package/dist/runtime-client.d.ts +0 -3
  63. package/dist/runtime-client.js +0 -4
  64. package/dist/runtime.client.d.ts +0 -2
  65. package/dist/runtime.client.js +0 -4
  66. package/dist/runtime.d.ts +0 -5
  67. package/dist/runtime.js +0 -12
  68. package/dist/runtime.server.d.ts +0 -2
  69. package/dist/runtime.server.js +0 -8
  70. package/dist/vite-plugins/sdk-context.d.ts +0 -4
  71. package/dist/vite-plugins/sdk-context.js +0 -67
@@ -0,0 +1,54 @@
1
+ import { rm, writeFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { globby } from 'globby';
4
+ import { outdent } from 'outdent';
5
+ import type { Model } from '../utils/createProjectModel.js';
6
+ import { isValidBackofficeComponent } from '../utils/isValidBackofficeComponent.js';
7
+
8
+ export async function writeVirtualExtensionFiles(
9
+ model: Model,
10
+ codegenDir: string
11
+ ) {
12
+ const existingFiles = await globby(`*.astro`, {
13
+ cwd: codegenDir,
14
+ onlyFiles: true,
15
+ });
16
+
17
+ for (const filename of existingFiles) {
18
+ const hasMatchingSourceFile = model.extensions.some(
19
+ (extension) => `${extension.config.compId}.astro` === filename
20
+ );
21
+
22
+ if (hasMatchingSourceFile) {
23
+ continue;
24
+ }
25
+
26
+ await rm(join(codegenDir, filename));
27
+ }
28
+
29
+ const backofficeExtensions = model.extensions.filter((extension) =>
30
+ isValidBackofficeComponent(extension.config)
31
+ );
32
+
33
+ for (const extension of backofficeExtensions) {
34
+ const originalEntrypoint = resolve(
35
+ model.rootDir,
36
+ extension.componentFilePath
37
+ );
38
+ const virtualEntrypoint = join(
39
+ codegenDir,
40
+ `${extension.config.compId}.astro`
41
+ );
42
+
43
+ await writeFile(
44
+ virtualEntrypoint,
45
+ outdent`
46
+ ---
47
+ import Component from '${originalEntrypoint}';
48
+ ---
49
+
50
+ <Component client:only="react" />
51
+ `
52
+ );
53
+ }
54
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["src", "test"],
4
+ "compilerOptions": {
5
+ "outDir": "build",
6
+ "declaration": true
7
+ }
8
+ }
@@ -0,0 +1,28 @@
1
+ import { defineConfig } from '@wix/tsup-configs/public-node';
2
+
3
+ export default defineConfig(
4
+ {
5
+ entry: ['src/index.ts'],
6
+ target: 'node20.9',
7
+ format: ['esm'],
8
+ outDir: 'build',
9
+ splitting: false,
10
+ external: ['astro', 'vite', /^astro:/],
11
+ dts: {
12
+ resolve: ['astro', 'vite', /^astro:/],
13
+ },
14
+ },
15
+ [
16
+ {
17
+ entry: ['src/middleware/auth.ts'],
18
+ target: 'node20.9',
19
+ format: ['esm'],
20
+ outDir: 'build-runtime',
21
+ splitting: false,
22
+ external: ['astro', 'vite', /^astro:/],
23
+ dts: {
24
+ resolve: ['astro', 'vite', /^astro:/],
25
+ },
26
+ },
27
+ ]
28
+ );
package/README.md DELETED
@@ -1,121 +0,0 @@
1
- # Wix Integration For Astro
2
-
3
- The Wix integration for Astro allows you to build custom frontends with Astro on top of the Wix Developer Platform. The integration provides a boilerplate-free development experience with a set of tools to help streamline your development with Wix.
4
-
5
- The main features of the Wix integration for Astro include:
6
-
7
- - **Easy SDK Integration**: Use the Wix SDK modules directly through a pre-initialized and contextually available `WixClient`.
8
- - **Session Management Middleware**: A middleware that manages a session cookie for the current site visitor.
9
- - **Adapter for Wix Hosting**: The integration provides an adapter for Wix hosting, allowing you to deploy your Astro project to Wix hosting.
10
-
11
- ## Getting Started
12
-
13
- The easiest way to get started with the Wix integration for Astro is to scaffold a new Astro project with one of the Wix templates. If you already have an Astro project or rather start with another template, you can add the Wix integration to an existing Astro project.
14
-
15
- ### Scaffold a New Astro Project with a Wix Template
16
-
17
- Wix provides a collection of Astro templates that are pre-configured with the Wix integration for Astro and also act as a starting point for different types of projects. Check out our Wix Astro templates on GitHub: [wix/headless-templates/astro](https://github.com/wix/headless-templates/tree/main/astro).
18
-
19
- ```bash
20
- # npm
21
- npm create astro@latest --template wix/headless-templates/astro/<template-name>
22
- # yarn
23
- yarn create astro@latest --template wix/headless-templates/astro/<template-name>
24
- # pnpm
25
- pnpm create astro@latest --template wix/headless-templates/astro/<template-name>
26
- ```
27
-
28
- Check the template's README for more information on how to get started with the template.
29
-
30
- ### Add the Wix Integration to an Existing Astro Project
31
-
32
- If you already have an Astro project or want to start with another template, you can add the Wix integration to your project.
33
-
34
- ```bash
35
- # npm
36
- npx astro add @wix/astro
37
- # yarn
38
- yarn astro add @wix/astro
39
- # pnpm
40
- pnpx astro add @wix/astro
41
- ```
42
-
43
- #### Setting up local development
44
-
45
- > 💡 If you are deploying your project to Wix, check out the guide on [local development with the Wix Edge CLI](../cli//local-development.md).
46
-
47
- The Wix integration requires the `WIX_CLIENT_ID` environment variable to be set. For local development, you can create a `.env.local` file in the root of your project and add the `WIX_CLIENT_ID` environment variable.
48
-
49
- ```properties
50
- WIX_CLIENT_ID=your-wix-client-id
51
- ```
52
-
53
- > ❓ Not sure what the Wix Client ID is or how to obtain it? Check out our documentation to [Create an OAuth App](https://dev.wix.com/docs/go-headless/getting-started/setup/authentication/create-an-oauth-app-for-visitors-and-members)
54
-
55
- ## Features
56
-
57
- ### Easy SDK Integration
58
-
59
- The Wix integration for Astro provides a pre-initialized and contextually available `WixClient` that allows you to use the Wix SDK modules directly in your Astro project.
60
-
61
- For example, to query your products from the Wix Stores API, you can just install the `@wix/stores` npm package and use the methods directly after importing them.
62
-
63
- ```js
64
- ---
65
- import { products } from "@wix/stores";
66
-
67
- const storeProducts = await products.queryProducts().find();
68
- ---
69
-
70
- <h1>Number of products in store: {storeProducts.items.length}</h1>
71
- ```
72
-
73
- #### SDK Modules in Astro Components frontmatter
74
-
75
- You can use any of the SDK modules in your Astro components frontmatter to fetch data at build time or on-demand. There's no need to create an explicit `WixClient` and methods can be called directly.
76
-
77
- ```astro
78
- ---
79
- import { products } from "@wix/stores";
80
-
81
- const storeProducts = await products.queryProducts().find();
82
- ---
83
-
84
- <h1>Products</h1>
85
-
86
- {storeProducts.map((product) => (
87
- <div>
88
- <h2>{product.name}</h2>
89
- <p>{product.description}</p>
90
- </div>
91
- ))}
92
- ```
93
-
94
- ##### Pre-rendering
95
-
96
- When used in pre-rendered components or pages, the SDK modules will use an automatically generated visitor session for the entire build. This means you'll only be able to access public data, and any data that requires a visitor session will be reset on each build.
97
-
98
- > 💡 If you are working with APIs that require a current visitor session, be sure to set the relevant pages / components to [on-demand rendering](#on-demand-rendering).
99
-
100
- ##### On-demand rendering
101
-
102
- When used in on-demand rendered components or pages, the SDK modules will use the current visitor session. This means you'll be able to access data that requires a visitor session, and the data will be fetched on-demand when the page is visited.
103
-
104
- Visitor session management is handled by the [Session Management Middleware](#session-management-middleware).
105
-
106
- #### SDK Modules in Scripts / UI Frameworks
107
-
108
- You can also use the SDK modules in your scripts or UI frameworks. Just import the modules and use them as you would in any other JavaScript environment.
109
-
110
- ```html
111
- <p>Products in store: <span id="productsCount">...</span></p>
112
- <script>
113
- import { products } from "@wix/stores";
114
-
115
- const storeProducts = await products.queryProducts().find();
116
-
117
- document.getElementById("productsCount").innerText = storeProducts.items.length;
118
- </script>
119
- ```
120
-
121
- In your scripts or UI framework components, your API calls will be authenticated with the current visitor session as managed by the [Session Management Middleware](#session-management-middleware).
@@ -1,5 +0,0 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import type { AuthenticationStrategy } from "@wix/sdk";
3
- export declare const authStrategyAsyncLocalStorage: AsyncLocalStorage<{
4
- auth: AuthenticationStrategy<void>;
5
- }>;
@@ -1,2 +0,0 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- export const authStrategyAsyncLocalStorage = new AsyncLocalStorage();
package/dist/client.d.ts DELETED
@@ -1,15 +0,0 @@
1
- import { categories, posts, tags } from "@wix/blog";
2
- import { items } from "@wix/data";
3
- export declare const getWixClient: ({ modules }?: {
4
- modules: {
5
- items: typeof items;
6
- posts: typeof posts;
7
- categories: typeof categories;
8
- tags: typeof tags;
9
- };
10
- }) => import("@wix/sdk").WixClient<undefined, import("@wix/sdk").IOAuthStrategy, {
11
- items: typeof items;
12
- posts: typeof posts;
13
- categories: typeof categories;
14
- tags: typeof tags;
15
- }>;
package/dist/client.js DELETED
@@ -1,16 +0,0 @@
1
- import { categories, posts, tags } from "@wix/blog";
2
- import { items } from "@wix/data";
3
- import { createClient, OAuthStrategy } from "@wix/sdk";
4
- export const getWixClient = ({ modules } = { modules: { items, posts, categories, tags } }) => {
5
- const { WIX_CLIENT_ID } = import.meta.env;
6
- if (!WIX_CLIENT_ID) {
7
- throw new Error(`❌ Wix Client ID is missing! Please create an ".env.local" file with WIX_CLIENT_ID.`);
8
- }
9
- const wixClient = createClient({
10
- modules,
11
- auth: OAuthStrategy({
12
- clientId: WIX_CLIENT_ID,
13
- }),
14
- });
15
- return wixClient;
16
- };
@@ -1,11 +0,0 @@
1
- import { APIMetadata, PublicMetadata } from '@wix/sdk-types';
2
- export declare const WixBIHeaderName = "x-wix-bi-gateway";
3
- export type WixBIHeaderValues = {
4
- ['environment']: 'js-sdk' | string;
5
- ['package-name']?: string;
6
- ['method-fqn']?: string;
7
- ['entity']?: string;
8
- };
9
- export declare function biHeaderGenerator(apiMetadata: APIMetadata, publicMetadata?: PublicMetadata, environment?: string): {
10
- [WixBIHeaderName]: string;
11
- };
@@ -1,17 +0,0 @@
1
- export const WixBIHeaderName = 'x-wix-bi-gateway';
2
- export function biHeaderGenerator(apiMetadata, publicMetadata, environment) {
3
- return {
4
- [WixBIHeaderName]: objectToKeyValue({
5
- environment: `js-sdk${environment ? `-${environment}` : ``}`,
6
- 'package-name': apiMetadata.packageName ?? publicMetadata?.PACKAGE_NAME,
7
- 'method-fqn': apiMetadata.methodFqn,
8
- entity: apiMetadata.entityFqdn,
9
- }),
10
- };
11
- }
12
- function objectToKeyValue(input) {
13
- return Object.entries(input)
14
- .filter(([_, value]) => Boolean(value))
15
- .map(([key, value]) => `${key}=${value}`)
16
- .join(',');
17
- }
@@ -1,4 +0,0 @@
1
- export declare function addListener(eventTarget: any, name: string, fn: Function): void;
2
- export declare function removeListener(eventTarget: any, name: string, fn: Function): void;
3
- export declare function loadFrame(src: string): HTMLIFrameElement;
4
- export declare function addPostMessageListener(state: string): Promise<unknown>;
@@ -1,43 +0,0 @@
1
- export function addListener(eventTarget, name, fn) {
2
- if (eventTarget.addEventListener) {
3
- eventTarget.addEventListener(name, fn);
4
- }
5
- else {
6
- eventTarget.attachEvent('on' + name, fn);
7
- }
8
- }
9
- export function removeListener(eventTarget, name, fn) {
10
- if (eventTarget.removeEventListener) {
11
- eventTarget.removeEventListener(name, fn);
12
- }
13
- else {
14
- eventTarget.detachEvent('on' + name, fn);
15
- }
16
- }
17
- export function loadFrame(src) {
18
- const iframe = document.createElement('iframe');
19
- iframe.style.display = 'none';
20
- iframe.src = src;
21
- return document.body.appendChild(iframe);
22
- }
23
- export function addPostMessageListener(state) {
24
- let responseHandler;
25
- let timeoutId;
26
- const msgReceivedOrTimeout = new Promise((resolve, reject) => {
27
- responseHandler = (e) => {
28
- if (!e.data || e.data.state !== state) {
29
- // A message not meant for us
30
- return;
31
- }
32
- resolve(e.data);
33
- };
34
- addListener(window, 'message', responseHandler);
35
- timeoutId = setTimeout(() => {
36
- reject(new Error('OAuth flow timed out'));
37
- }, 120000);
38
- });
39
- return msgReceivedOrTimeout.finally(() => {
40
- clearTimeout(timeoutId);
41
- removeListener(window, 'message', responseHandler);
42
- });
43
- }
@@ -1,42 +0,0 @@
1
- export interface OauthPKCE {
2
- codeVerifier: string;
3
- codeChallenge: string;
4
- state: string;
5
- }
6
- export interface OauthData extends OauthPKCE {
7
- originalUri: string;
8
- redirectUri: string;
9
- }
10
- export interface OauthPKCE {
11
- codeVerifier: string;
12
- codeChallenge: string;
13
- state: string;
14
- }
15
- export interface Token {
16
- value: string;
17
- }
18
- export interface AccessToken extends Token {
19
- expiresAt: number;
20
- }
21
- export declare enum TokenRole {
22
- NONE = "none",
23
- VISITOR = "visitor",
24
- MEMBER = "member"
25
- }
26
- export interface TokenResponse {
27
- access_token: string;
28
- expires_in: number;
29
- refresh_token: string | null;
30
- token_type: string;
31
- scope?: string | null;
32
- }
33
- export declare const getMemberTokensForDirectLogin: (sessionToken: string) => Promise<{
34
- clientId: string;
35
- tokens: {
36
- accessToken: AccessToken;
37
- refreshToken: {
38
- value: string;
39
- role: TokenRole;
40
- };
41
- };
42
- }>;
@@ -1,119 +0,0 @@
1
- import { redirects } from '@wix/redirects';
2
- import { loadFrame, addPostMessageListener } from './iframeUtils.js';
3
- import { biHeaderGenerator } from './bi-header-generator.js';
4
- import { wixContext } from '@wix/sdk-context';
5
- import { generateRandomCodeVerifier, calculatePKCECodeChallenge, generateRandomState } from 'oauth4webapi';
6
- const DEFAULT_API_URL = 'www.wixapis.com';
7
- export var TokenRole;
8
- (function (TokenRole) {
9
- TokenRole["NONE"] = "none";
10
- TokenRole["VISITOR"] = "visitor";
11
- TokenRole["MEMBER"] = "member";
12
- })(TokenRole || (TokenRole = {}));
13
- const generatePKCE = async () => {
14
- const codeVerifier = generateRandomCodeVerifier();
15
- const pkceState = await calculatePKCECodeChallenge(codeVerifier);
16
- return {
17
- codeChallenge: pkceState,
18
- codeVerifier: codeVerifier,
19
- state: generateRandomState(),
20
- };
21
- };
22
- const getAuthorizationUrlWithOptions = async (oauthData, responseMode, prompt, sessionToken) => {
23
- const { redirectSession } = await redirects.createRedirectSession({
24
- auth: {
25
- authRequest: {
26
- redirectUri: oauthData.redirectUri,
27
- ...(oauthData.redirectUri && {
28
- redirectUri: oauthData.redirectUri,
29
- }),
30
- codeChallenge: oauthData.codeChallenge,
31
- codeChallengeMethod: 'S256',
32
- responseMode,
33
- responseType: 'code',
34
- scope: 'offline_access',
35
- state: oauthData.state,
36
- clientId: wixContext['clientId'],
37
- ...(sessionToken && { sessionToken }),
38
- },
39
- prompt: redirects.Prompt[prompt],
40
- },
41
- });
42
- return {
43
- authUrl: redirectSession.fullUrl,
44
- authorizationEndpoint: redirectSession.urlDetails.endpoint,
45
- sessionToken: redirectSession.sessionToken,
46
- };
47
- };
48
- const fetchTokens = async (payload, headers = {}) => {
49
- const res = await fetch(`https://${DEFAULT_API_URL}/oauth2/token`, {
50
- method: 'POST',
51
- body: JSON.stringify(payload),
52
- headers: {
53
- ...biHeaderGenerator({
54
- entityFqdn: 'wix.identity.oauth.v1.refresh_token',
55
- methodFqn: 'wix.identity.oauth2.v1.Oauth2Ng.Token',
56
- packageName: '@wix/sdk',
57
- }),
58
- 'Content-Type': 'application/json',
59
- ...headers,
60
- },
61
- });
62
- if (res.status !== 200) {
63
- let responseJson;
64
- try {
65
- responseJson = await res.json();
66
- }
67
- catch { }
68
- throw new Error(`Failed to fetch tokens from OAuth API: ${res.statusText}. request id: ${res.headers.get('x-request-id')}. ${responseJson ? `Response: ${JSON.stringify(responseJson)}` : ''}`);
69
- }
70
- const json = await res.json();
71
- return json;
72
- };
73
- function getCurrentDate() {
74
- return Math.floor(Date.now() / 1000);
75
- }
76
- function createAccessToken(accessToken, expiresIn) {
77
- const now = getCurrentDate();
78
- return { value: accessToken, expiresAt: Number(expiresIn) + now };
79
- }
80
- const getMemberTokens = async (code, state, oauthData) => {
81
- if (!code || !state) {
82
- throw new Error('Missing code or _state');
83
- }
84
- else if (state !== oauthData.state) {
85
- throw new Error('Invalid _state');
86
- }
87
- const tokensResponse = await fetchTokens({
88
- clientId: wixContext['clientId'],
89
- grantType: 'authorization_code',
90
- ...(oauthData.redirectUri && { redirectUri: oauthData.redirectUri }),
91
- code,
92
- codeVerifier: oauthData.codeVerifier,
93
- });
94
- return {
95
- clientId: wixContext['clientId'],
96
- tokens: {
97
- accessToken: createAccessToken(tokensResponse.access_token, tokensResponse.expires_in),
98
- refreshToken: {
99
- value: tokensResponse.refresh_token,
100
- role: TokenRole.MEMBER,
101
- },
102
- }
103
- };
104
- };
105
- export const getMemberTokensForDirectLogin = async (sessionToken) => {
106
- const oauthPKCE = await generatePKCE();
107
- const { authUrl } = await getAuthorizationUrlWithOptions(oauthPKCE, 'web_message', 'none', sessionToken);
108
- const iframePromise = addPostMessageListener(oauthPKCE.state);
109
- const iframeEl = loadFrame(authUrl);
110
- return iframePromise
111
- .then((res) => {
112
- return getMemberTokens(res.code, res.state, oauthPKCE);
113
- })
114
- .finally(() => {
115
- if (document.body.contains(iframeEl)) {
116
- iframeEl.parentElement?.removeChild(iframeEl);
117
- }
118
- });
119
- };