@wix/astro 1.0.15 → 1.0.16

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.
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,17 @@
1
+ // src/context/elevated.ts
2
+ import { AppStrategy, createClient } from "@wix/sdk";
3
+ import { WIX_CLIENT_ID } from "astro:env/client";
4
+ import {
5
+ WIX_CLIENT_INSTANCE_ID,
6
+ WIX_CLIENT_PUBLIC_KEY,
7
+ WIX_CLIENT_SECRET
8
+ } from "astro:env/server";
9
+ var elevatedContextClient = createClient({
10
+ auth: AppStrategy({
11
+ appId: WIX_CLIENT_ID,
12
+ appSecret: WIX_CLIENT_SECRET,
13
+ instanceId: WIX_CLIENT_INSTANCE_ID,
14
+ publicKey: WIX_CLIENT_PUBLIC_KEY
15
+ })
16
+ });
17
+ elevatedContextClient.enableContext("global", { elevated: true });
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,20 @@
1
+ // src/context/non-elevated.ts
2
+ import { createClient, OAuthStrategy } from "@wix/sdk";
3
+ import { WIX_CLIENT_ID } from "astro:env/client";
4
+
5
+ // src/utils/authAsyncLocalStorage.ts
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ var authAsyncLocalStorage = new AsyncLocalStorage();
8
+
9
+ // src/context/non-elevated.ts
10
+ var contextClient = createClient({
11
+ get auth() {
12
+ const store = authAsyncLocalStorage.getStore();
13
+ const auth = OAuthStrategy({
14
+ clientId: WIX_CLIENT_ID,
15
+ tokens: store?.sessionTokens?.tokens
16
+ });
17
+ return auth;
18
+ }
19
+ });
20
+ contextClient.enableContext("global");
@@ -1,19 +1,20 @@
1
- // src/middleware/auth.ts
2
- import { AppStrategy, createClient, OAuthStrategy } from "@wix/sdk";
3
- import { WIX_CLIENT_ID as WIX_CLIENT_ID3 } from "astro:env/client";
4
- import {
5
- WIX_CLIENT_INSTANCE_ID,
6
- WIX_CLIENT_PUBLIC_KEY,
7
- WIX_CLIENT_SECRET
8
- } from "astro:env/server";
9
-
10
- // src/utils/authStrategyAsyncLocalStorage.ts
1
+ // src/utils/authAsyncLocalStorage.ts
11
2
  import { AsyncLocalStorage } from "node:async_hooks";
12
- var authStrategyAsyncLocalStorage = new AsyncLocalStorage();
3
+ var authAsyncLocalStorage = new AsyncLocalStorage();
4
+
5
+ // src/utils/generateVisitorTokens.ts
6
+ import { OAuthStrategy } from "@wix/sdk";
7
+ import { WIX_CLIENT_ID } from "astro:env/client";
8
+ var auth = OAuthStrategy({
9
+ clientId: WIX_CLIENT_ID
10
+ });
11
+ async function generateVisitorTokens() {
12
+ return auth.generateVisitorTokens();
13
+ }
13
14
 
14
15
  // src/utils/getSessionTokensFromCookie.ts
15
16
  import { TokenRole } from "@wix/sdk";
16
- import { WIX_CLIENT_ID } from "astro:env/client";
17
+ import { WIX_CLIENT_ID as WIX_CLIENT_ID2 } from "astro:env/client";
17
18
  import { z } from "astro/zod";
18
19
  var tokensSchema = z.object({
19
20
  clientId: z.string(),
@@ -29,23 +30,23 @@ var tokensSchema = z.object({
29
30
  })
30
31
  });
31
32
  function getSessionTokensFromCookie(context) {
32
- if (context.isPrerendered) {
33
- return;
34
- }
35
- const rawCookie = context.cookies.get("wixSession")?.json();
36
- if (rawCookie) {
37
- const tokensParseResult = tokensSchema.safeParse(rawCookie);
38
- if (tokensParseResult.success && tokensParseResult.data.clientId === WIX_CLIENT_ID) {
39
- return tokensParseResult.data;
33
+ if (!context.isPrerendered) {
34
+ const rawCookie = context.cookies.get("wixSession")?.json();
35
+ if (rawCookie) {
36
+ const tokensParseResult = tokensSchema.safeParse(rawCookie);
37
+ if (tokensParseResult.success && tokensParseResult.data.clientId === WIX_CLIENT_ID2) {
38
+ return tokensParseResult.data;
39
+ }
40
40
  }
41
41
  }
42
+ return null;
42
43
  }
43
44
 
44
45
  // src/utils/saveSessionTokensToCookie.ts
45
- import { WIX_CLIENT_ID as WIX_CLIENT_ID2 } from "astro:env/client";
46
+ import { WIX_CLIENT_ID as WIX_CLIENT_ID3 } from "astro:env/client";
46
47
  function sessionCookieJson(tokens) {
47
48
  return {
48
- clientId: WIX_CLIENT_ID2,
49
+ clientId: WIX_CLIENT_ID3,
49
50
  tokens
50
51
  };
51
52
  }
@@ -57,59 +58,15 @@ function saveSessionTokensToCookie(context, tokens) {
57
58
  }
58
59
 
59
60
  // src/middleware/auth.ts
60
- var contextClient = createClient({
61
- auth: {
62
- async getAuthHeaders(host) {
63
- const store = authStrategyAsyncLocalStorage.getStore();
64
- if (!store?.auth) {
65
- throw new Error(
66
- "No authentication strategy found in the current context"
67
- );
68
- }
69
- return store.auth.getAuthHeaders(host);
70
- }
71
- }
72
- });
73
- var elevatedContextClient = createClient({
74
- auth: {
75
- async getAuthHeaders(host) {
76
- const store = authStrategyAsyncLocalStorage.getStore();
77
- if (!store?.elevatedAuth) {
78
- throw new Error(
79
- "No elevated authentication strategy found in the current context"
80
- );
81
- }
82
- return store.elevatedAuth.getAuthHeaders(host);
83
- }
84
- }
85
- });
86
- contextClient.enableContext("global");
87
- elevatedContextClient.enableContext("global", { elevated: true });
88
61
  var onRequest = async (context, next) => {
89
- const sessionTokensFromCookie = getSessionTokensFromCookie(context);
90
- const auth = OAuthStrategy({
91
- clientId: WIX_CLIENT_ID3
92
- });
93
- if (sessionTokensFromCookie) {
94
- auth.setTokens(sessionTokensFromCookie.tokens);
95
- } else {
96
- auth.setTokens(await auth.generateVisitorTokens());
97
- }
98
- const elevatedAuth = AppStrategy({
99
- appId: WIX_CLIENT_ID3,
100
- appSecret: WIX_CLIENT_SECRET,
101
- instanceId: WIX_CLIENT_INSTANCE_ID,
102
- publicKey: WIX_CLIENT_PUBLIC_KEY
62
+ const store = {
63
+ sessionTokens: getSessionTokensFromCookie(context)
64
+ };
65
+ const response = await authAsyncLocalStorage.run(store, () => {
66
+ return next();
103
67
  });
104
- const response = await authStrategyAsyncLocalStorage.run(
105
- {
106
- auth,
107
- elevatedAuth
108
- },
109
- () => next()
110
- );
111
- if (!context.isPrerendered && sessionTokensFromCookie?.tokens.accessToken.expiresAt !== auth.getTokens().accessToken.expiresAt) {
112
- saveSessionTokensToCookie(context, auth.getTokens());
68
+ if (!context.isPrerendered && store.sessionTokens == null) {
69
+ saveSessionTokensToCookie(context, await generateVisitorTokens());
113
70
  }
114
71
  return response;
115
72
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/astro",
3
- "version": "1.0.15",
3
+ "version": "1.0.16",
4
4
  "devDependencies": {
5
5
  "@wix/dashboard": "^1.3.35",
6
6
  "@wix/sdk": "^1.15.17",
@@ -46,5 +46,5 @@
46
46
  ]
47
47
  }
48
48
  },
49
- "falconPackageHash": "03baaa6edb871e335e34c1c6f47130585ee742e48350a4b908c708b5"
49
+ "falconPackageHash": "6148e131e45c16f42c1c8b3fa4778e5d51ffc096a593673996084c97"
50
50
  }
@@ -0,0 +1,18 @@
1
+ import { AppStrategy, createClient } from '@wix/sdk';
2
+ import { WIX_CLIENT_ID } from 'astro:env/client';
3
+ import {
4
+ WIX_CLIENT_INSTANCE_ID,
5
+ WIX_CLIENT_PUBLIC_KEY,
6
+ WIX_CLIENT_SECRET,
7
+ } from 'astro:env/server';
8
+
9
+ const elevatedContextClient = createClient({
10
+ auth: AppStrategy({
11
+ appId: WIX_CLIENT_ID,
12
+ appSecret: WIX_CLIENT_SECRET,
13
+ instanceId: WIX_CLIENT_INSTANCE_ID,
14
+ publicKey: WIX_CLIENT_PUBLIC_KEY,
15
+ }),
16
+ });
17
+
18
+ elevatedContextClient.enableContext('global', { elevated: true });
@@ -0,0 +1,18 @@
1
+ import { createClient, OAuthStrategy } from '@wix/sdk';
2
+ import { WIX_CLIENT_ID } from 'astro:env/client';
3
+ import { authAsyncLocalStorage } from '../utils/authAsyncLocalStorage.js';
4
+
5
+ const contextClient = createClient({
6
+ get auth() {
7
+ const store = authAsyncLocalStorage.getStore();
8
+
9
+ const auth = OAuthStrategy({
10
+ clientId: WIX_CLIENT_ID,
11
+ tokens: store?.sessionTokens?.tokens,
12
+ });
13
+
14
+ return auth;
15
+ },
16
+ });
17
+
18
+ contextClient.enableContext('global');
@@ -1,6 +1,5 @@
1
1
  import { join } from 'node:path';
2
2
 
3
- const SRC_DIR = 'src';
4
-
3
+ export const SRC_DIR = 'src';
5
4
  export const GIT_IGNORED_DIR = '.wix';
6
5
  export const EXTENSIONS_DIR = join(SRC_DIR, 'extensions');
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ import type { Model } from './types.js';
8
8
  import { EXTENSIONS_DIR, GIT_IGNORED_DIR } from './directories.js';
9
9
  import { patchAstroInlineScripts } from './plugins/patchAstroInlineScripts.js';
10
10
  import { patchGlobal } from './plugins/patchGlobal.js';
11
+ import { setupSsrContext } from './plugins/setupSsrContext.js';
11
12
  import { createProjectModel } from './utils/createProjectModel.js';
12
13
  import { outputDir, writeJson } from './utils/fs-utils.js';
13
14
  import { generateAppManifest } from './utils/generateAppManifest.js';
@@ -117,7 +118,11 @@ const createIntegration = (): AstroIntegration => {
117
118
  service: passthroughImageService(),
118
119
  },
119
120
  vite: {
120
- plugins: [patchGlobal(), patchAstroInlineScripts()],
121
+ plugins: [
122
+ patchGlobal(),
123
+ patchAstroInlineScripts(),
124
+ setupSsrContext(rootDir),
125
+ ],
121
126
  },
122
127
  });
123
128
 
@@ -1,84 +1,20 @@
1
1
  import type { MiddlewareHandler } from 'astro';
2
- import { AppStrategy, createClient, OAuthStrategy } from '@wix/sdk';
3
- import { WIX_CLIENT_ID } from 'astro:env/client';
4
- import {
5
- WIX_CLIENT_INSTANCE_ID,
6
- WIX_CLIENT_PUBLIC_KEY,
7
- WIX_CLIENT_SECRET,
8
- } from 'astro:env/server';
9
- import { authStrategyAsyncLocalStorage } from '../utils/authStrategyAsyncLocalStorage.js';
2
+ import { authAsyncLocalStorage } from '../utils/authAsyncLocalStorage.js';
3
+ import { generateVisitorTokens } from '../utils/generateVisitorTokens.js';
10
4
  import { getSessionTokensFromCookie } from '../utils/getSessionTokensFromCookie.js';
11
5
  import { saveSessionTokensToCookie } from '../utils/saveSessionTokensToCookie.js';
12
6
 
13
- const contextClient = createClient({
14
- auth: {
15
- async getAuthHeaders(host) {
16
- const store = authStrategyAsyncLocalStorage.getStore();
17
-
18
- if (!store?.auth) {
19
- throw new Error(
20
- 'No authentication strategy found in the current context'
21
- );
22
- }
23
-
24
- return store.auth.getAuthHeaders(host);
25
- },
26
- },
27
- });
28
-
29
- const elevatedContextClient = createClient({
30
- auth: {
31
- async getAuthHeaders(host) {
32
- const store = authStrategyAsyncLocalStorage.getStore();
33
-
34
- if (!store?.elevatedAuth) {
35
- throw new Error(
36
- 'No elevated authentication strategy found in the current context'
37
- );
38
- }
39
-
40
- return store.elevatedAuth.getAuthHeaders(host);
41
- },
42
- },
43
- });
44
-
45
- contextClient.enableContext('global');
46
- elevatedContextClient.enableContext('global', { elevated: true });
47
-
48
7
  export const onRequest: MiddlewareHandler = async (context, next) => {
49
- const sessionTokensFromCookie = getSessionTokensFromCookie(context);
50
-
51
- const auth = OAuthStrategy({
52
- clientId: WIX_CLIENT_ID,
53
- });
8
+ const store = {
9
+ sessionTokens: getSessionTokensFromCookie(context),
10
+ };
54
11
 
55
- if (sessionTokensFromCookie) {
56
- auth.setTokens(sessionTokensFromCookie.tokens);
57
- } else {
58
- auth.setTokens(await auth.generateVisitorTokens());
59
- }
60
-
61
- const elevatedAuth = AppStrategy({
62
- appId: WIX_CLIENT_ID,
63
- appSecret: WIX_CLIENT_SECRET,
64
- instanceId: WIX_CLIENT_INSTANCE_ID,
65
- publicKey: WIX_CLIENT_PUBLIC_KEY,
12
+ const response = await authAsyncLocalStorage.run(store, () => {
13
+ return next();
66
14
  });
67
15
 
68
- const response = await authStrategyAsyncLocalStorage.run(
69
- {
70
- auth,
71
- elevatedAuth,
72
- },
73
- () => next()
74
- );
75
-
76
- if (
77
- !context.isPrerendered &&
78
- sessionTokensFromCookie?.tokens.accessToken.expiresAt !==
79
- auth.getTokens().accessToken.expiresAt
80
- ) {
81
- saveSessionTokensToCookie(context, auth.getTokens());
16
+ if (!context.isPrerendered && store.sessionTokens == null) {
17
+ saveSessionTokensToCookie(context, await generateVisitorTokens());
82
18
  }
83
19
 
84
20
  return response;
@@ -0,0 +1,47 @@
1
+ import { extname, join } from 'node:path';
2
+ import type { PluginOption } from 'vite';
3
+ import { outdent } from 'outdent';
4
+ import { SRC_DIR } from '../directories.js';
5
+
6
+ export function setupSsrContext(rootDir: string): PluginOption {
7
+ const srcDir = join(rootDir, SRC_DIR);
8
+
9
+ const nonElevatedSetupUrl = new URL(
10
+ '../build-runtime/context/non-elevated.js',
11
+ import.meta.url
12
+ );
13
+ const elevatedSetupUrl = new URL(
14
+ '../build-runtime/context/elevated.js',
15
+ import.meta.url
16
+ );
17
+
18
+ return {
19
+ applyToEnvironment(environment) {
20
+ return environment.name === 'ssr';
21
+ },
22
+ name: 'setup-ssr-context',
23
+ transform(code, id) {
24
+ if (!id.startsWith(srcDir)) {
25
+ return null;
26
+ }
27
+
28
+ const extension = extname(id);
29
+
30
+ if (
31
+ extension !== '.js' &&
32
+ extension !== '.astro' &&
33
+ extension !== '.ts' &&
34
+ extension !== '.tsx'
35
+ ) {
36
+ return null;
37
+ }
38
+
39
+ return outdent`
40
+ import '${nonElevatedSetupUrl}';
41
+ import '${elevatedSetupUrl}';
42
+
43
+ ${code}
44
+ `;
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,6 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { SessionTokens } from './getSessionTokensFromCookie.js';
3
+
4
+ export const authAsyncLocalStorage = new AsyncLocalStorage<{
5
+ sessionTokens: null | SessionTokens;
6
+ }>();
@@ -5,7 +5,7 @@ import {
5
5
  writeFile,
6
6
  } from 'node:fs/promises';
7
7
  import { EOL } from 'node:os';
8
- import { dirname } from 'node:path';
8
+ import { dirname, relative } from 'node:path';
9
9
 
10
10
  function toJsonString(object: unknown, opts?: { spaces: number }) {
11
11
  return JSON.stringify(object, null, opts?.spaces).concat(EOL);
@@ -35,3 +35,8 @@ export function pathExists(path: string) {
35
35
  export async function outputDir(dir: string) {
36
36
  await mkdir(dir, { recursive: true });
37
37
  }
38
+
39
+ export function toRelativePath(from: string, to: string) {
40
+ const rel = relative(dirname(from), to).replaceAll('\\', '/');
41
+ return rel.startsWith('.') ? rel : `./${rel}`;
42
+ }
@@ -0,0 +1,10 @@
1
+ import { OAuthStrategy } from '@wix/sdk';
2
+ import { WIX_CLIENT_ID } from 'astro:env/client';
3
+
4
+ const auth = OAuthStrategy({
5
+ clientId: WIX_CLIENT_ID,
6
+ });
7
+
8
+ export async function generateVisitorTokens() {
9
+ return auth.generateVisitorTokens();
10
+ }
@@ -17,21 +17,25 @@ const tokensSchema = z.object({
17
17
  }),
18
18
  });
19
19
 
20
- export function getSessionTokensFromCookie(context: APIContext) {
21
- if (context.isPrerendered) {
22
- return;
23
- }
20
+ export type SessionTokens = z.infer<typeof tokensSchema>;
24
21
 
25
- const rawCookie = context.cookies.get('wixSession')?.json();
22
+ export function getSessionTokensFromCookie(
23
+ context: APIContext
24
+ ): null | SessionTokens {
25
+ if (!context.isPrerendered) {
26
+ const rawCookie = context.cookies.get('wixSession')?.json();
26
27
 
27
- if (rawCookie) {
28
- const tokensParseResult = tokensSchema.safeParse(rawCookie);
28
+ if (rawCookie) {
29
+ const tokensParseResult = tokensSchema.safeParse(rawCookie);
29
30
 
30
- if (
31
- tokensParseResult.success &&
32
- tokensParseResult.data.clientId === WIX_CLIENT_ID
33
- ) {
34
- return tokensParseResult.data;
31
+ if (
32
+ tokensParseResult.success &&
33
+ tokensParseResult.data.clientId === WIX_CLIENT_ID
34
+ ) {
35
+ return tokensParseResult.data;
36
+ }
35
37
  }
36
38
  }
39
+
40
+ return null;
37
41
  }
@@ -6,6 +6,7 @@ import { match } from 'variant';
6
6
  import type { Component } from '../components.js';
7
7
  import type { Model } from '../types.js';
8
8
  import { isValidBackofficeComponent } from '../utils/isValidBackofficeComponent.js';
9
+ import { toRelativePath } from './fs-utils.js';
9
10
 
10
11
  export async function writeVirtualBackofficeExtensionFiles(
11
12
  model: Model,
@@ -44,7 +45,7 @@ export async function writeVirtualBackofficeExtensionFiles(
44
45
  virtualEntrypoint,
45
46
  outdent`
46
47
  ---
47
- import Component from '${originalEntrypoint}';
48
+ import Component from '${toRelativePath(virtualEntrypoint, originalEntrypoint)}';
48
49
  ---
49
50
 
50
51
  <div>
@@ -3,6 +3,7 @@ import { join, resolve } from 'node:path';
3
3
  import { globby } from 'globby';
4
4
  import { outdent } from 'outdent';
5
5
  import type { Model } from '../types.js';
6
+ import { toRelativePath } from './fs-utils.js';
6
7
  import { isValidServicePluginComponent } from './isValidServicePluginComponent.js';
7
8
 
8
9
  export async function writeVirtualServicePluginExtensionFiles(
@@ -57,7 +58,7 @@ export async function writeVirtualServicePluginExtensionFiles(
57
58
 
58
59
  client.enableContext('global');
59
60
 
60
- await import('${originalEntrypoint}');
61
+ await import('${toRelativePath(virtualEntrypoint, originalEntrypoint)}');
61
62
 
62
63
  if (olderClient) {
63
64
  olderClient.enableContext('global');
@@ -3,6 +3,7 @@ import { join, resolve } from 'node:path';
3
3
  import { globby } from 'globby';
4
4
  import { outdent } from 'outdent';
5
5
  import type { Model } from '../types.js';
6
+ import { toRelativePath } from './fs-utils.js';
6
7
  import { isValidWebhookComponent } from './isValidWebhookComponent.js';
7
8
 
8
9
  export async function writeVirtualWebhookExtensionFiles(
@@ -55,7 +56,7 @@ export async function writeVirtualWebhookExtensionFiles(
55
56
 
56
57
  client.enableContext('global');
57
58
 
58
- await import('${originalEntrypoint}');
59
+ await import('${toRelativePath(virtualEntrypoint, originalEntrypoint)}');
59
60
 
60
61
  if (olderClient) {
61
62
  olderClient.enableContext('global');
package/tsup.config.mjs CHANGED
@@ -39,6 +39,8 @@ export default defineConfig([
39
39
  'src/middleware/auth.ts',
40
40
  'src/routes/webhooks.ts',
41
41
  'src/routes/service-plugins.ts',
42
+ 'src/context/elevated.ts',
43
+ 'src/context/non-elevated.ts',
42
44
  ],
43
45
  target: 'node20.9',
44
46
  format: ['esm'],
@@ -1,7 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import type { AuthenticationStrategy } from '@wix/sdk';
3
-
4
- export const authStrategyAsyncLocalStorage = new AsyncLocalStorage<{
5
- auth: AuthenticationStrategy<undefined> | null;
6
- elevatedAuth: AuthenticationStrategy<undefined> | null;
7
- }>();