@wix/astro 0.3.4 → 1.0.2

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 (78) hide show
  1. package/build/index.d.ts +5 -0
  2. package/build/index.js +124997 -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/middleware/auth.d.ts +5 -0
  7. package/build-runtime/middleware/auth.js +8027 -0
  8. package/build-runtime/routes/webhooks.d.ts +5 -0
  9. package/build-runtime/routes/webhooks.js +11 -0
  10. package/package.json +37 -47
  11. package/runtime/entry.astro +26 -0
  12. package/src/directories.ts +14 -0
  13. package/src/env.d.ts +9 -0
  14. package/src/index.ts +283 -0
  15. package/src/middleware/auth.ts +86 -0
  16. package/src/plugins/patchGlobal.ts +20 -0
  17. package/src/routes/webhooks.ts +10 -0
  18. package/src/utils/authStrategyAsyncLocalStorage.ts +7 -0
  19. package/src/utils/checkIsDynamicPageRequest.ts +17 -0
  20. package/src/utils/createProjectModel.ts +87 -0
  21. package/src/utils/generateAppManifest.ts +49 -0
  22. package/src/utils/getSessionTokensFromCookie.ts +38 -0
  23. package/src/utils/isValidBackofficeComponent.ts +15 -0
  24. package/src/utils/isValidWebhookComponent.ts +9 -0
  25. package/src/utils/loadExtension.ts +59 -0
  26. package/src/utils/saveSessionTokensToCookie.ts +17 -0
  27. package/src/utils/writeVirtualBackofficeExtensionFiles.ts +56 -0
  28. package/src/utils/writeVirtualWebhookExtensionFiles.ts +70 -0
  29. package/tsconfig.json +8 -0
  30. package/tsup.config.mjs +28 -0
  31. package/README.md +0 -121
  32. package/dist/auth-context.d.ts +0 -5
  33. package/dist/auth-context.js +0 -2
  34. package/dist/client.d.ts +0 -15
  35. package/dist/client.js +0 -16
  36. package/dist/components/login-helpers/bi-header-generator.d.ts +0 -11
  37. package/dist/components/login-helpers/bi-header-generator.js +0 -17
  38. package/dist/components/login-helpers/iframeUtils.d.ts +0 -4
  39. package/dist/components/login-helpers/iframeUtils.js +0 -43
  40. package/dist/components/login-helpers/login-helpers.d.ts +0 -42
  41. package/dist/components/login-helpers/login-helpers.js +0 -119
  42. package/dist/components/login.astro +0 -872
  43. package/dist/entrypoints/server.d.ts +0 -13
  44. package/dist/entrypoints/server.js +0 -36
  45. package/dist/helpers/index.d.ts +0 -1
  46. package/dist/helpers/index.js +0 -1
  47. package/dist/index.d.ts +0 -5
  48. package/dist/index.js +0 -4
  49. package/dist/integration.d.ts +0 -22
  50. package/dist/integration.js +0 -233
  51. package/dist/loaders/blog.d.ts +0 -2
  52. package/dist/loaders/blog.js +0 -48
  53. package/dist/loaders/index.d.ts +0 -2
  54. package/dist/loaders/index.js +0 -2
  55. package/dist/middleware.d.ts +0 -2
  56. package/dist/middleware.js +0 -89
  57. package/dist/routes/auth/callback.d.ts +0 -3
  58. package/dist/routes/auth/callback.js +0 -52
  59. package/dist/routes/auth/constants.d.ts +0 -5
  60. package/dist/routes/auth/constants.js +0 -5
  61. package/dist/routes/auth/login.d.ts +0 -3
  62. package/dist/routes/auth/login.js +0 -26
  63. package/dist/routes/auth/logout-callback.d.ts +0 -3
  64. package/dist/routes/auth/logout-callback.js +0 -9
  65. package/dist/routes/auth/logout.d.ts +0 -3
  66. package/dist/routes/auth/logout.js +0 -10
  67. package/dist/routes/auth/runtime.d.ts +0 -5
  68. package/dist/routes/auth/runtime.js +0 -7
  69. package/dist/runtime-client.d.ts +0 -3
  70. package/dist/runtime-client.js +0 -4
  71. package/dist/runtime.client.d.ts +0 -2
  72. package/dist/runtime.client.js +0 -4
  73. package/dist/runtime.d.ts +0 -5
  74. package/dist/runtime.js +0 -12
  75. package/dist/runtime.server.d.ts +0 -2
  76. package/dist/runtime.server.js +0 -8
  77. package/dist/vite-plugins/sdk-context.d.ts +0 -4
  78. package/dist/vite-plugins/sdk-context.js +0 -67
@@ -0,0 +1,49 @@
1
+ import type {
2
+ AppManifest,
3
+ BackofficePage,
4
+ Webhook,
5
+ } from '@wix/cli-app-manifest';
6
+ import { ComponentType } from '@wix/ambassador-devcenter-components-v1-component/types';
7
+ import type { Model } from './createProjectModel.js';
8
+
9
+ export function generateAppManifest(model: Model): AppManifest {
10
+ return {
11
+ appId: model.app.appId,
12
+ components: model.extensions
13
+ .map((extension) => extension.config)
14
+ .map((config) => {
15
+ switch (config.compType) {
16
+ case ComponentType.BACK_OFFICE_PAGE:
17
+ if (config.compData.backOfficePage.iframeUrl) {
18
+ return config;
19
+ }
20
+
21
+ return {
22
+ ...config,
23
+ compData: {
24
+ backOfficePage: {
25
+ ...config.compData.backOfficePage,
26
+ iframeUrl: `_wix/extensions/backoffice/${config.compId}`,
27
+ },
28
+ },
29
+ } satisfies BackofficePage;
30
+ case ComponentType.WEBHOOK:
31
+ if (config.compData.webhook.callbackUrl) {
32
+ return config;
33
+ }
34
+
35
+ return {
36
+ ...config,
37
+ compData: {
38
+ webhook: {
39
+ ...config.compData.webhook,
40
+ callbackUrl: `_wix/extensions/webhooks/${config.compId}`,
41
+ },
42
+ },
43
+ } satisfies Webhook;
44
+ default:
45
+ return config;
46
+ }
47
+ }),
48
+ };
49
+ }
@@ -0,0 +1,38 @@
1
+ import type { APIContext } from 'astro';
2
+ import { TokenRole } from '@wix/sdk';
3
+ import { WIX_CLIENT_ID } from 'astro:env/client';
4
+ import { z } from 'astro/zod';
5
+ import { checkIsDynamicPageRequest } from './checkIsDynamicPageRequest.js';
6
+
7
+ const tokensSchema = z.object({
8
+ clientId: z.string(),
9
+ tokens: z.object({
10
+ accessToken: z.object({
11
+ expiresAt: z.number(),
12
+ value: z.string(),
13
+ }),
14
+ refreshToken: z.object({
15
+ role: z.nativeEnum(TokenRole),
16
+ value: z.string(),
17
+ }),
18
+ }),
19
+ });
20
+
21
+ export function getSessionTokensFromCookie(context: APIContext) {
22
+ if (!checkIsDynamicPageRequest(context)) {
23
+ return;
24
+ }
25
+
26
+ const rawCookie = context.cookies.get('wixSession')?.json();
27
+
28
+ if (rawCookie) {
29
+ const tokensParseResult = tokensSchema.safeParse(rawCookie);
30
+
31
+ if (
32
+ tokensParseResult.success &&
33
+ tokensParseResult.data.clientId === WIX_CLIENT_ID
34
+ ) {
35
+ return tokensParseResult.data;
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,15 @@
1
+ import type { Component } from '@wix/cli-app-manifest';
2
+ import { ComponentType } from '@wix/ambassador-devcenter-components-v1-component/types';
3
+
4
+ export function isValidBackofficeComponent(component: Component) {
5
+ return (
6
+ (component.compType === ComponentType.BACK_OFFICE_PAGE &&
7
+ !component.compData.backOfficePage.iframeUrl) ||
8
+ (component.compType === ComponentType.BACK_OFFICE_EXTENSION_WIDGET &&
9
+ !component.compData.backOfficeExtensionWidget.iframeUrl) ||
10
+ (component.compType === ComponentType.BACK_OFFICE_EXTENSION_MENU_ITEM &&
11
+ !component.compData.backOfficeExtensionMenuItem.iframeUrl) ||
12
+ (component.compType === ComponentType.BACK_OFFICE_MODAL &&
13
+ !component.compData.backOfficeModal.iframeUrl)
14
+ );
15
+ }
@@ -0,0 +1,9 @@
1
+ import type { Component } from '@wix/cli-app-manifest';
2
+ import { ComponentType } from '@wix/ambassador-devcenter-components-v1-component/types';
3
+
4
+ export function isValidWebhookComponent(component: Component) {
5
+ return (
6
+ component.compType === ComponentType.WEBHOOK &&
7
+ !component.compData.webhook.callbackUrl
8
+ );
9
+ }
@@ -0,0 +1,59 @@
1
+ import { join } from 'node:path';
2
+ import type { Schema } from 'zod';
3
+ import { pathExists, readJson } from '@wix/cli-fs';
4
+ import { globby } from 'globby';
5
+ import { outdent } from 'outdent';
6
+
7
+ export async function loadExtension<T>({
8
+ directory,
9
+ fileName,
10
+ rootDir,
11
+ schema,
12
+ }: {
13
+ directory: string;
14
+ fileName: string;
15
+ rootDir: string;
16
+ schema: Schema<T>;
17
+ }) {
18
+ const extensions: Array<{
19
+ componentFilePath: string;
20
+ config: T;
21
+ cwd: string;
22
+ }> = [];
23
+
24
+ const extensionsPaths = await globby(join(directory, '*'), {
25
+ cwd: rootDir,
26
+ onlyDirectories: true,
27
+ });
28
+
29
+ for (const extensionPath of extensionsPaths) {
30
+ const configDir = join(extensionPath, `${fileName}.json`);
31
+
32
+ if (!(await pathExists(configDir))) {
33
+ throw new Error('Missing extension config file');
34
+ }
35
+
36
+ const extensionConfigFile = await readJson(configDir);
37
+ const parsedExtensionConfig = schema.safeParse(extensionConfigFile);
38
+
39
+ if (!parsedExtensionConfig.success) {
40
+ throw new Error(outdent`
41
+ Invalid extension configuration:
42
+
43
+ ${parsedExtensionConfig.error.errors
44
+ .map((e) => `${e.path.join('.')}: ${e.message}`)
45
+ .join('\n')}
46
+ `);
47
+ }
48
+
49
+ const componentFilePath = join(extensionPath, `${fileName}.tsx`);
50
+
51
+ extensions.push({
52
+ componentFilePath,
53
+ config: parsedExtensionConfig.data,
54
+ cwd: extensionPath,
55
+ });
56
+ }
57
+
58
+ return extensions;
59
+ }
@@ -0,0 +1,17 @@
1
+ import type { Tokens } from '@wix/sdk';
2
+ import type { APIContext } from 'astro';
3
+ import { WIX_CLIENT_ID } from 'astro:env/client';
4
+
5
+ function sessionCookieJson(tokens: Tokens) {
6
+ return {
7
+ clientId: WIX_CLIENT_ID,
8
+ tokens,
9
+ };
10
+ }
11
+
12
+ export function saveSessionTokensToCookie(context: APIContext, tokens: Tokens) {
13
+ context.cookies.set('wixSession', sessionCookieJson(tokens), {
14
+ path: '/',
15
+ secure: true,
16
+ });
17
+ }
@@ -0,0 +1,56 @@
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 writeVirtualBackofficeExtensionFiles(
9
+ model: Model,
10
+ codegenDir: string
11
+ ) {
12
+ const backofficeExtensions = model.extensions.filter((extension) =>
13
+ isValidBackofficeComponent(extension.config)
14
+ );
15
+
16
+ const existingFiles = await globby(`*.astro`, {
17
+ cwd: codegenDir,
18
+ onlyFiles: true,
19
+ });
20
+
21
+ for (const filename of existingFiles) {
22
+ const hasMatchingSourceFile = backofficeExtensions.some(
23
+ (extension) => `${extension.config.compId}.astro` === filename
24
+ );
25
+
26
+ if (hasMatchingSourceFile) {
27
+ continue;
28
+ }
29
+
30
+ await rm(join(codegenDir, filename));
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
+ <div>
51
+ <Component client:only="react" />
52
+ </div>
53
+ `
54
+ );
55
+ }
56
+ }
@@ -0,0 +1,70 @@
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 { isValidWebhookComponent } from './isValidWebhookComponent.js';
7
+
8
+ export async function writeVirtualWebhookExtensionFiles(
9
+ model: Model,
10
+ codegenDir: string
11
+ ) {
12
+ const webhookExtensions = model.extensions.filter((extension) =>
13
+ isValidWebhookComponent(extension.config)
14
+ );
15
+
16
+ const existingFiles = await globby(`*.ts`, {
17
+ cwd: codegenDir,
18
+ onlyFiles: true,
19
+ });
20
+
21
+ for (const filename of existingFiles) {
22
+ const hasMatchingSourceFile = webhookExtensions.some(
23
+ (extension) => `${extension.config.compId}.ts` === filename
24
+ );
25
+
26
+ if (hasMatchingSourceFile) {
27
+ continue;
28
+ }
29
+
30
+ await rm(join(codegenDir, filename));
31
+ }
32
+
33
+ for (const extension of webhookExtensions) {
34
+ const originalEntrypoint = resolve(extension.cwd, 'event.ts');
35
+ const virtualEntrypoint = join(codegenDir, `${extension.config.compId}.ts`);
36
+
37
+ await writeFile(
38
+ virtualEntrypoint,
39
+ outdent`
40
+ import type { APIRoute } from 'astro';
41
+ import { AppStrategy, createClient } from '@wix/sdk';
42
+ import { WIX_CLIENT_ID } from 'astro:env/client';
43
+ import { WIX_CLIENT_PUBLIC_KEY, WIX_CLIENT_SECRET } from 'astro:env/server';
44
+
45
+ const client = createClient({
46
+ auth: AppStrategy({
47
+ appId: WIX_CLIENT_ID,
48
+ appSecret: WIX_CLIENT_SECRET,
49
+ publicKey: WIX_CLIENT_PUBLIC_KEY,
50
+ }),
51
+ });
52
+
53
+ const olderClient = globalThis.__wix_context__.client;
54
+
55
+ client.enableContext('global');
56
+
57
+ await import('${originalEntrypoint}');
58
+
59
+ if (olderClient) {
60
+ olderClient.enableContext('global');
61
+ }
62
+
63
+ export const ALL: APIRoute = async (context) => {
64
+ await client.webhooks.processRequest(context.request);
65
+ return new Response('OK');
66
+ };
67
+ `
68
+ );
69
+ }
70
+ }
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', 'src/routes/webhooks.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
- }>;