@plasmicapp/loader-fetcher 1.0.23 → 1.0.24

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.
package/dist/api.d.ts CHANGED
@@ -1,132 +1,132 @@
1
- export interface ComponentMeta {
2
- id: string;
3
- usedComponents: string[];
4
- projectId: string;
5
- name: string;
6
- displayName: string;
7
- cssFile: string;
8
- path: string | undefined;
9
- isPage: boolean;
10
- plumeType?: string;
11
- entry: string;
12
- isCode: boolean;
13
- isGlobalContextProvider: boolean;
14
- pageMetadata?: PageMetadata;
15
- metadata?: Record<string, string>;
16
- }
17
- export interface PageMeta extends ComponentMeta {
18
- isPage: true;
19
- path: string;
20
- plumeType: never;
21
- pageMetadata: PageMetadata;
22
- }
23
- export interface PageMetadata {
24
- path: string;
25
- title?: string | null;
26
- description?: string | null;
27
- openGraphImageUrl?: string | null;
28
- }
29
- export interface GlobalGroupMeta {
30
- id: string;
31
- projectId: string;
32
- name: string;
33
- type: string;
34
- contextFile: string;
35
- useName: string;
36
- }
37
- export interface ProjectMeta {
38
- id: string;
39
- teamId?: string;
40
- indirect?: boolean;
41
- name: string;
42
- version: string;
43
- remoteFonts: FontMeta[];
44
- globalContextsProviderFileName: string;
45
- }
46
- export interface FontMeta {
47
- url: string;
48
- }
49
- interface GlobalVariantSplitContent {
50
- type: 'global-variant';
51
- projectId: string;
52
- group: string;
53
- variant: string;
54
- }
55
- interface Slice {
56
- id: string;
57
- contents: GlobalVariantSplitContent[];
58
- externalId?: string;
59
- }
60
- export interface ExperimentSlice extends Slice {
61
- prob: number;
62
- }
63
- export interface SegmentSlice extends Slice {
64
- cond: any;
65
- }
66
- export interface ExperimentSplit {
67
- id: string;
68
- externalId?: string;
69
- type: 'experiment';
70
- slices: ExperimentSlice[];
71
- }
72
- export interface SegmentSplit {
73
- id: string;
74
- externalId?: string;
75
- type: 'segment';
76
- slices: SegmentSlice[];
77
- }
78
- export declare type Split = ExperimentSplit | SegmentSplit;
79
- export interface LoaderBundleOutput {
80
- modules: {
81
- browser: (CodeModule | AssetModule)[];
82
- server: (CodeModule | AssetModule)[];
83
- };
84
- external: string[];
85
- components: ComponentMeta[];
86
- globalGroups: GlobalGroupMeta[];
87
- projects: ProjectMeta[];
88
- activeSplits: Split[];
89
- }
90
- export interface LoaderHtmlOutput {
91
- html: string;
92
- }
93
- export interface CodeModule {
94
- fileName: string;
95
- code: string;
96
- imports: string[];
97
- type: 'code';
98
- }
99
- export interface AssetModule {
100
- fileName: string;
101
- source: string;
102
- type: 'asset';
103
- }
104
- export declare const isBrowser: boolean;
105
- export declare class Api {
106
- private opts;
107
- private host;
108
- constructor(opts: {
109
- projects: {
110
- id: string;
111
- token: string;
112
- }[];
113
- host?: string;
114
- });
115
- fetchLoaderData(projectIds: string[], opts: {
116
- platform?: 'react' | 'nextjs' | 'gatsby';
117
- preview?: boolean;
118
- browserOnly?: boolean;
119
- i18nKeyScheme?: 'content' | 'hash';
120
- }): Promise<LoaderBundleOutput>;
121
- private parseJsonResponse;
122
- fetchHtmlData(opts: {
123
- projectId: string;
124
- component: string;
125
- hydrate?: boolean;
126
- embedHydrate?: boolean;
127
- }): Promise<LoaderHtmlOutput>;
128
- private makeGetHeaders;
129
- private makePostHeaders;
130
- private makeAuthHeaders;
131
- }
132
- export {};
1
+ export interface ComponentMeta {
2
+ id: string;
3
+ usedComponents: string[];
4
+ projectId: string;
5
+ name: string;
6
+ displayName: string;
7
+ cssFile: string;
8
+ path: string | undefined;
9
+ isPage: boolean;
10
+ plumeType?: string;
11
+ entry: string;
12
+ isCode: boolean;
13
+ isGlobalContextProvider: boolean;
14
+ pageMetadata?: PageMetadata;
15
+ metadata?: Record<string, string>;
16
+ }
17
+ export interface PageMeta extends ComponentMeta {
18
+ isPage: true;
19
+ path: string;
20
+ plumeType: never;
21
+ pageMetadata: PageMetadata;
22
+ }
23
+ export interface PageMetadata {
24
+ path: string;
25
+ title?: string | null;
26
+ description?: string | null;
27
+ openGraphImageUrl?: string | null;
28
+ }
29
+ export interface GlobalGroupMeta {
30
+ id: string;
31
+ projectId: string;
32
+ name: string;
33
+ type: string;
34
+ contextFile: string;
35
+ useName: string;
36
+ }
37
+ export interface ProjectMeta {
38
+ id: string;
39
+ teamId?: string;
40
+ indirect?: boolean;
41
+ name: string;
42
+ version: string;
43
+ remoteFonts: FontMeta[];
44
+ globalContextsProviderFileName: string;
45
+ }
46
+ export interface FontMeta {
47
+ url: string;
48
+ }
49
+ interface GlobalVariantSplitContent {
50
+ type: 'global-variant';
51
+ projectId: string;
52
+ group: string;
53
+ variant: string;
54
+ }
55
+ interface Slice {
56
+ id: string;
57
+ contents: GlobalVariantSplitContent[];
58
+ externalId?: string;
59
+ }
60
+ export interface ExperimentSlice extends Slice {
61
+ prob: number;
62
+ }
63
+ export interface SegmentSlice extends Slice {
64
+ cond: any;
65
+ }
66
+ export interface ExperimentSplit {
67
+ id: string;
68
+ externalId?: string;
69
+ type: 'experiment';
70
+ slices: ExperimentSlice[];
71
+ }
72
+ export interface SegmentSplit {
73
+ id: string;
74
+ externalId?: string;
75
+ type: 'segment';
76
+ slices: SegmentSlice[];
77
+ }
78
+ export type Split = ExperimentSplit | SegmentSplit;
79
+ export interface LoaderBundleOutput {
80
+ modules: {
81
+ browser: (CodeModule | AssetModule)[];
82
+ server: (CodeModule | AssetModule)[];
83
+ };
84
+ external: string[];
85
+ components: ComponentMeta[];
86
+ globalGroups: GlobalGroupMeta[];
87
+ projects: ProjectMeta[];
88
+ activeSplits: Split[];
89
+ }
90
+ export interface LoaderHtmlOutput {
91
+ html: string;
92
+ }
93
+ export interface CodeModule {
94
+ fileName: string;
95
+ code: string;
96
+ imports: string[];
97
+ type: 'code';
98
+ }
99
+ export interface AssetModule {
100
+ fileName: string;
101
+ source: string;
102
+ type: 'asset';
103
+ }
104
+ export declare const isBrowser: boolean;
105
+ export declare class Api {
106
+ private opts;
107
+ private host;
108
+ constructor(opts: {
109
+ projects: {
110
+ id: string;
111
+ token: string;
112
+ }[];
113
+ host?: string;
114
+ });
115
+ fetchLoaderData(projectIds: string[], opts: {
116
+ platform?: 'react' | 'nextjs' | 'gatsby';
117
+ preview?: boolean;
118
+ browserOnly?: boolean;
119
+ i18nKeyScheme?: 'content' | 'hash';
120
+ }): Promise<LoaderBundleOutput>;
121
+ private parseJsonResponse;
122
+ fetchHtmlData(opts: {
123
+ projectId: string;
124
+ component: string;
125
+ hydrate?: boolean;
126
+ embedHydrate?: boolean;
127
+ }): Promise<LoaderHtmlOutput>;
128
+ private makeGetHeaders;
129
+ private makePostHeaders;
130
+ private makeAuthHeaders;
131
+ }
132
+ export {};
package/dist/fetcher.d.ts CHANGED
@@ -1,28 +1,28 @@
1
- import { LoaderBundleOutput } from './api';
2
- export interface FetcherOptions {
3
- projects: {
4
- id: string;
5
- version?: string;
6
- token: string;
7
- }[];
8
- cache?: LoaderBundleCache;
9
- platform?: 'react' | 'nextjs' | 'gatsby';
10
- preview?: boolean;
11
- host?: string;
12
- i18nKeyScheme?: 'content' | 'hash';
13
- }
14
- export interface LoaderBundleCache {
15
- set: (data: LoaderBundleOutput) => Promise<void>;
16
- get: () => Promise<LoaderBundleOutput>;
17
- }
18
- export declare class PlasmicModulesFetcher {
19
- private opts;
20
- private api;
21
- private curFetch;
22
- constructor(opts: FetcherOptions);
23
- fetchAllData(): Promise<LoaderBundleOutput>;
24
- private getCachedOrFetch;
25
- private doFetch;
26
- private cacheBundleInNodeServer;
27
- }
28
- export declare function internal_getCachedBundleInNodeServer(opts: FetcherOptions): LoaderBundleOutput | undefined;
1
+ import { LoaderBundleOutput } from './api';
2
+ export interface FetcherOptions {
3
+ projects: {
4
+ id: string;
5
+ version?: string;
6
+ token: string;
7
+ }[];
8
+ cache?: LoaderBundleCache;
9
+ platform?: 'react' | 'nextjs' | 'gatsby';
10
+ preview?: boolean;
11
+ host?: string;
12
+ i18nKeyScheme?: 'content' | 'hash';
13
+ }
14
+ export interface LoaderBundleCache {
15
+ set: (data: LoaderBundleOutput) => Promise<void>;
16
+ get: () => Promise<LoaderBundleOutput>;
17
+ }
18
+ export declare class PlasmicModulesFetcher {
19
+ private opts;
20
+ private api;
21
+ private curFetch;
22
+ constructor(opts: FetcherOptions);
23
+ fetchAllData(): Promise<LoaderBundleOutput>;
24
+ private getCachedOrFetch;
25
+ private doFetch;
26
+ private cacheBundleInNodeServer;
27
+ }
28
+ export declare function internal_getCachedBundleInNodeServer(opts: FetcherOptions): LoaderBundleOutput | undefined;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,4 @@
1
- export { Api, AssetModule, CodeModule, ComponentMeta, ExperimentSlice, FontMeta, GlobalGroupMeta, LoaderBundleOutput, LoaderHtmlOutput, PageMeta, PageMetadata, ProjectMeta, SegmentSlice, Split, } from './api';
2
- export { FetcherOptions, internal_getCachedBundleInNodeServer, LoaderBundleCache, PlasmicModulesFetcher, } from './fetcher';
1
+ export type { AssetModule, CodeModule, ComponentMeta, ExperimentSlice, FontMeta, GlobalGroupMeta, LoaderBundleOutput, LoaderHtmlOutput, PageMeta, PageMetadata, ProjectMeta, SegmentSlice, Split, } from "./api";
2
+ export { Api } from "./api";
3
+ export type { FetcherOptions, LoaderBundleCache } from "./fetcher";
4
+ export { internal_getCachedBundleInNodeServer, PlasmicModulesFetcher, } from "./fetcher";
package/dist/index.js CHANGED
@@ -1,8 +1,248 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __export = (target, all) => {
23
+ for (var name in all)
24
+ __defProp(target, name, { get: all[name], enumerable: true });
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (let key of __getOwnPropNames(from))
29
+ if (!__hasOwnProp.call(to, key) && key !== except)
30
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
+ }
32
+ return to;
33
+ };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
+ // If the importer is in node compatibility mode or this is not an ESM
36
+ // file that has been converted to a CommonJS file using a Babel-
37
+ // compatible transform (i.e. "__esModule" has not been set), then set
38
+ // "default" to the CommonJS "module.exports" for node compatibility.
39
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
+ mod
41
+ ));
42
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
43
+ var __async = (__this, __arguments, generator) => {
44
+ return new Promise((resolve, reject) => {
45
+ var fulfilled = (value) => {
46
+ try {
47
+ step(generator.next(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var rejected = (value) => {
53
+ try {
54
+ step(generator.throw(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
60
+ step((generator = generator.apply(__this, __arguments)).next());
61
+ });
62
+ };
1
63
 
2
- 'use strict'
64
+ // src/index.ts
65
+ var src_exports = {};
66
+ __export(src_exports, {
67
+ Api: () => Api,
68
+ PlasmicModulesFetcher: () => PlasmicModulesFetcher,
69
+ internal_getCachedBundleInNodeServer: () => internal_getCachedBundleInNodeServer
70
+ });
71
+ module.exports = __toCommonJS(src_exports);
3
72
 
4
- if (process.env.NODE_ENV === 'production') {
5
- module.exports = require('./loader-fetcher.cjs.production.min.js')
6
- } else {
7
- module.exports = require('./loader-fetcher.cjs.development.js')
73
+ // src/api.ts
74
+ var import_isomorphic_unfetch = __toESM(require("@plasmicapp/isomorphic-unfetch"));
75
+ var VERSION = "10";
76
+ var isBrowser = typeof window !== "undefined" && window != null && typeof window.document !== "undefined";
77
+ var Api = class {
78
+ constructor(opts) {
79
+ this.opts = opts;
80
+ var _a;
81
+ this.host = (_a = opts.host) != null ? _a : "https://codegen.plasmic.app";
82
+ }
83
+ fetchLoaderData(projectIds, opts) {
84
+ return __async(this, null, function* () {
85
+ var _a, _b;
86
+ const { platform, preview } = opts;
87
+ const query = new URLSearchParams([
88
+ ["platform", platform != null ? platform : "react"],
89
+ ...projectIds.map((projectId) => ["projectId", projectId]),
90
+ ...opts.browserOnly ? [["browserOnly", "true"]] : [],
91
+ ...opts.i18nKeyScheme ? [["i18nKeyScheme", opts.i18nKeyScheme]] : []
92
+ ]).toString();
93
+ const url = `${this.host}/api/v1/loader/code/${preview ? "preview" : "published"}?${query}`;
94
+ const resp = yield (0, import_isomorphic_unfetch.default)(url, {
95
+ method: "GET",
96
+ headers: this.makeGetHeaders()
97
+ });
98
+ if (resp.status >= 400) {
99
+ const error = yield this.parseJsonResponse(resp);
100
+ throw new Error(
101
+ `Error fetching loader data: ${(_b = (_a = error == null ? void 0 : error.error) == null ? void 0 : _a.message) != null ? _b : resp.statusText}`
102
+ );
103
+ }
104
+ const json = yield this.parseJsonResponse(resp);
105
+ return json;
106
+ });
107
+ }
108
+ parseJsonResponse(resp) {
109
+ return __async(this, null, function* () {
110
+ const text = yield resp.text();
111
+ try {
112
+ return JSON.parse(text);
113
+ } catch (err) {
114
+ throw new Error(
115
+ `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`
116
+ );
117
+ }
118
+ });
119
+ }
120
+ fetchHtmlData(opts) {
121
+ return __async(this, null, function* () {
122
+ const { projectId, component, embedHydrate, hydrate } = opts;
123
+ const query = new URLSearchParams([
124
+ ["projectId", projectId],
125
+ ["component", component],
126
+ ["embedHydrate", embedHydrate ? "1" : "0"],
127
+ ["hydrate", hydrate ? "1" : "0"]
128
+ ]).toString();
129
+ const resp = yield (0, import_isomorphic_unfetch.default)(`${this.host}/api/v1/loader/html?${query}`, {
130
+ method: "GET",
131
+ headers: this.makeGetHeaders()
132
+ });
133
+ const json = yield resp.json();
134
+ return json;
135
+ });
136
+ }
137
+ makeGetHeaders() {
138
+ return __spreadValues({
139
+ "x-plasmic-loader-version": VERSION
140
+ }, this.makeAuthHeaders());
141
+ }
142
+ // @ts-ignore
143
+ makePostHeaders() {
144
+ return __spreadValues({
145
+ "x-plasmic-loader-version": VERSION,
146
+ "Content-Type": "application/json"
147
+ }, this.makeAuthHeaders());
148
+ }
149
+ makeAuthHeaders() {
150
+ const tokens = this.opts.projects.map((p) => `${p.id}:${p.token}`).join(",");
151
+ return {
152
+ "x-plasmic-api-project-tokens": tokens
153
+ };
154
+ }
155
+ };
156
+
157
+ // src/fetcher.ts
158
+ var PlasmicModulesFetcher = class {
159
+ constructor(opts) {
160
+ this.opts = opts;
161
+ this.curFetch = void 0;
162
+ this.api = new Api({
163
+ projects: opts.projects,
164
+ host: opts.host
165
+ });
166
+ }
167
+ fetchAllData() {
168
+ return __async(this, null, function* () {
169
+ const bundle = yield this.getCachedOrFetch();
170
+ this.cacheBundleInNodeServer(bundle);
171
+ return bundle;
172
+ });
173
+ }
174
+ getCachedOrFetch() {
175
+ return __async(this, null, function* () {
176
+ if (this.opts.cache) {
177
+ const cachedData = yield this.opts.cache.get();
178
+ if (cachedData) {
179
+ return cachedData;
180
+ }
181
+ }
182
+ if (this.curFetch) {
183
+ return yield this.curFetch;
184
+ }
185
+ console.debug("Plasmic: doing a fresh fetch...");
186
+ this.curFetch = this.doFetch();
187
+ const data = yield this.curFetch;
188
+ this.curFetch = void 0;
189
+ return data;
190
+ });
191
+ }
192
+ doFetch() {
193
+ return __async(this, null, function* () {
194
+ const data = yield this.api.fetchLoaderData(
195
+ this.opts.projects.map(
196
+ (p) => p.version ? `${p.id}@${p.version}` : p.id
197
+ ),
198
+ {
199
+ platform: this.opts.platform,
200
+ preview: this.opts.preview,
201
+ i18nKeyScheme: this.opts.i18nKeyScheme,
202
+ browserOnly: isBrowser
203
+ }
204
+ );
205
+ if (this.opts.cache) {
206
+ yield this.opts.cache.set(data);
207
+ }
208
+ console.debug(
209
+ `Plasmic: fetched designs for ${data.projects.map((p) => `"${p.name}" (${p.id}@${p.version})`).join(", ")}`
210
+ );
211
+ return data;
212
+ });
213
+ }
214
+ cacheBundleInNodeServer(bundle) {
215
+ if (isBrowser) {
216
+ return;
217
+ }
218
+ const global = globalThis;
219
+ if (global.__PLASMIC_BUNDLES === void 0) {
220
+ global.__PLASMIC_BUNDLES = {};
221
+ }
222
+ global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;
223
+ }
224
+ };
225
+ function internal_getCachedBundleInNodeServer(opts) {
226
+ var _a;
227
+ if (isBrowser) {
228
+ throw new Error(`Should not be consulting Node server cache in browser`);
229
+ }
230
+ const global = globalThis;
231
+ return (_a = global.__PLASMIC_BUNDLES) == null ? void 0 : _a[getBundleKey(opts)];
232
+ }
233
+ function getBundleKey({
234
+ host,
235
+ platform,
236
+ i18nKeyScheme,
237
+ preview,
238
+ projects
239
+ }) {
240
+ return JSON.stringify({
241
+ host,
242
+ platform,
243
+ i18nKeyScheme,
244
+ preview,
245
+ projects
246
+ });
8
247
  }
248
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/api.ts", "../src/fetcher.ts"],
4
+ "sourcesContent": ["export type {\n AssetModule,\n CodeModule,\n ComponentMeta,\n ExperimentSlice,\n FontMeta,\n GlobalGroupMeta,\n LoaderBundleOutput,\n LoaderHtmlOutput,\n PageMeta,\n PageMetadata,\n ProjectMeta,\n SegmentSlice,\n Split,\n} from \"./api\";\nexport { Api } from \"./api\";\nexport type { FetcherOptions, LoaderBundleCache } from \"./fetcher\";\nexport {\n internal_getCachedBundleInNodeServer,\n PlasmicModulesFetcher,\n} from \"./fetcher\";\n", "import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '10';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`\n );\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n", "import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n const global = globalThis as GlobalWithBundles;\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n const global = globalThis as GlobalWithBundles;\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;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S,qCACd,MACgC;AApGlC;AAqGE,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAEA,QAAM,SAAS;AACf,UAAO,YAAO,sBAAP,mBAA2B,aAAa,IAAI;AACrD;AAEA,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAmB;AACjB,SAAO,KAAK,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;",
6
+ "names": ["fetch"]
7
+ }
package/package.json CHANGED
@@ -1,8 +1,14 @@
1
1
  {
2
- "version": "1.0.23",
2
+ "version": "1.0.24",
3
3
  "license": "MIT",
4
- "main": "dist/index.js",
5
- "typings": "dist/index.d.ts",
4
+ "types": "./dist/index.d.ts",
5
+ "main": "./dist/index.js",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "default": "./dist/index.js"
10
+ }
11
+ },
6
12
  "files": [
7
13
  "dist"
8
14
  ],
@@ -10,52 +16,30 @@
10
16
  "node": ">=10"
11
17
  },
12
18
  "scripts": {
13
- "start": "tsdx watch",
14
- "build": "tsdx build --target node",
19
+ "build": "yarn build:types && yarn build:index",
20
+ "build:types": "yarn tsc",
21
+ "build:index": "node ../../build.mjs ./src/index.ts",
15
22
  "postbuild": "node ../../print-module-api.js ./packages/loader-fetcher/dist/index.js > index-api.txt",
16
23
  "yalcp": "yalc publish --push",
17
24
  "test": "yarn --cwd=../.. test",
18
- "lint": "tsdx lint",
25
+ "lint": "eslint",
19
26
  "prepare": "if-env PREPARE_NO_BUILD=true || yarn build",
20
27
  "size": "size-limit",
21
28
  "analyze": "size-limit --why"
22
29
  },
23
- "husky": {
24
- "hooks": {
25
- "pre-commit": "tsdx lint"
26
- }
27
- },
28
- "prettier": {
29
- "printWidth": 80,
30
- "semi": true,
31
- "singleQuote": true,
32
- "trailingComma": "es5"
33
- },
34
30
  "name": "@plasmicapp/loader-fetcher",
35
31
  "author": "Chung Wu",
36
- "module": "dist/loader-fetcher.esm.js",
37
32
  "size-limit": [
38
33
  {
39
- "path": "dist/loader-fetcher.cjs.production.min.js",
40
- "limit": "10 KB"
41
- },
42
- {
43
- "path": "dist/loader-fetcher.esm.js",
34
+ "path": "dist/index.js",
44
35
  "limit": "10 KB"
45
36
  }
46
37
  ],
47
- "devDependencies": {
48
- "@size-limit/preset-small-lib": "^4.11.0",
49
- "husky": "^6.0.0",
50
- "size-limit": "^4.11.0",
51
- "tsdx": "^0.14.1",
52
- "tslib": "^2.2.0"
53
- },
54
38
  "dependencies": {
55
39
  "@plasmicapp/isomorphic-unfetch": "^1.0.1"
56
40
  },
57
41
  "publishConfig": {
58
42
  "access": "public"
59
43
  },
60
- "gitHead": "aed79bb7319dc8f42c185c212f9ba23f26591fd4"
44
+ "gitHead": "1d6d699a0dfb9781ecac5e8df1dfc3a690c43559"
61
45
  }
@@ -1,169 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- var fetch = _interopDefault(require('@plasmicapp/isomorphic-unfetch'));
8
-
9
- const VERSION = '10';
10
- const isBrowser = typeof window !== 'undefined' && window != null && typeof window.document !== 'undefined';
11
- class Api {
12
- constructor(opts) {
13
- var _opts$host;
14
- this.opts = opts;
15
- this.host = (_opts$host = opts.host) != null ? _opts$host : 'https://codegen.plasmic.app';
16
- }
17
- async fetchLoaderData(projectIds, opts) {
18
- const {
19
- platform,
20
- preview
21
- } = opts;
22
- const query = new URLSearchParams([['platform', platform != null ? platform : 'react'], ...projectIds.map(projectId => ['projectId', projectId]), ...(opts.browserOnly ? [['browserOnly', 'true']] : []), ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : [])]).toString();
23
- const url = `${this.host}/api/v1/loader/code/${preview ? 'preview' : 'published'}?${query}`;
24
- const resp = await fetch(url, {
25
- method: 'GET',
26
- headers: this.makeGetHeaders()
27
- });
28
- if (resp.status >= 400) {
29
- var _error$error$message, _error$error;
30
- const error = await this.parseJsonResponse(resp);
31
- throw new Error(`Error fetching loader data: ${(_error$error$message = error == null ? void 0 : (_error$error = error.error) == null ? void 0 : _error$error.message) != null ? _error$error$message : resp.statusText}`);
32
- }
33
- const json = await this.parseJsonResponse(resp);
34
- return json;
35
- }
36
- async parseJsonResponse(resp) {
37
- const text = await resp.text();
38
- try {
39
- return JSON.parse(text);
40
- } catch (err) {
41
- throw new Error(`Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`);
42
- }
43
- }
44
- async fetchHtmlData(opts) {
45
- const {
46
- projectId,
47
- component,
48
- embedHydrate,
49
- hydrate
50
- } = opts;
51
- const query = new URLSearchParams([['projectId', projectId], ['component', component], ['embedHydrate', embedHydrate ? '1' : '0'], ['hydrate', hydrate ? '1' : '0']]).toString();
52
- const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {
53
- method: 'GET',
54
- headers: this.makeGetHeaders()
55
- });
56
- const json = await resp.json();
57
- return json;
58
- }
59
- makeGetHeaders() {
60
- return {
61
- 'x-plasmic-loader-version': VERSION,
62
- ...this.makeAuthHeaders()
63
- };
64
- }
65
- // @ts-ignore
66
- makePostHeaders() {
67
- return {
68
- 'x-plasmic-loader-version': VERSION,
69
- 'Content-Type': 'application/json',
70
- ...this.makeAuthHeaders()
71
- };
72
- }
73
- makeAuthHeaders() {
74
- const tokens = this.opts.projects.map(p => `${p.id}:${p.token}`).join(',');
75
- return {
76
- 'x-plasmic-api-project-tokens': tokens
77
- };
78
- }
79
- }
80
-
81
- class PlasmicModulesFetcher {
82
- constructor(opts) {
83
- this.opts = opts;
84
- this.curFetch = undefined;
85
- this.api = new Api({
86
- projects: opts.projects,
87
- host: opts.host
88
- });
89
- }
90
- async fetchAllData() {
91
- // getCachedOrFetched uses a cache defined by the user.
92
- const bundle = await this.getCachedOrFetch();
93
- // For React Server Components (Next.js 13+),
94
- // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.
95
- // We don't want to pass them via normal page props because that will be serialized to the browser.
96
- // Instead, we pass the bundle (including the server modules) via the Node `global` variable.
97
- //
98
- // cacheBundleInNodeServer caches a bundle in the Node server process.
99
- this.cacheBundleInNodeServer(bundle);
100
- return bundle;
101
- }
102
- async getCachedOrFetch() {
103
- if (this.opts.cache) {
104
- const cachedData = await this.opts.cache.get();
105
- if (cachedData) {
106
- return cachedData;
107
- }
108
- }
109
- if (this.curFetch) {
110
- return await this.curFetch;
111
- }
112
- console.debug('Plasmic: doing a fresh fetch...');
113
- this.curFetch = this.doFetch();
114
- const data = await this.curFetch;
115
- this.curFetch = undefined;
116
- return data;
117
- }
118
- async doFetch() {
119
- const data = await this.api.fetchLoaderData(this.opts.projects.map(p => p.version ? `${p.id}@${p.version}` : p.id), {
120
- platform: this.opts.platform,
121
- preview: this.opts.preview,
122
- i18nKeyScheme: this.opts.i18nKeyScheme,
123
- browserOnly: isBrowser
124
- });
125
- if (this.opts.cache) {
126
- await this.opts.cache.set(data);
127
- }
128
- console.debug(`Plasmic: fetched designs for ${data.projects.map(p => `"${p.name}" (${p.id}@${p.version})`).join(', ')}`);
129
- return data;
130
- }
131
- cacheBundleInNodeServer(bundle) {
132
- if (isBrowser) {
133
- return;
134
- }
135
- const global = globalThis;
136
- if (global.__PLASMIC_BUNDLES === undefined) {
137
- global.__PLASMIC_BUNDLES = {};
138
- }
139
- global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;
140
- }
141
- }
142
- function internal_getCachedBundleInNodeServer(opts) {
143
- var _global$__PLASMIC_BUN;
144
- if (isBrowser) {
145
- throw new Error(`Should not be consulting Node server cache in browser`);
146
- }
147
- const global = globalThis;
148
- return (_global$__PLASMIC_BUN = global.__PLASMIC_BUNDLES) == null ? void 0 : _global$__PLASMIC_BUN[getBundleKey(opts)];
149
- }
150
- function getBundleKey({
151
- host,
152
- platform,
153
- i18nKeyScheme,
154
- preview,
155
- projects
156
- }) {
157
- return JSON.stringify({
158
- host,
159
- platform,
160
- i18nKeyScheme,
161
- preview,
162
- projects
163
- });
164
- }
165
-
166
- exports.Api = Api;
167
- exports.PlasmicModulesFetcher = PlasmicModulesFetcher;
168
- exports.internal_getCachedBundleInNodeServer = internal_getCachedBundleInNodeServer;
169
- //# sourceMappingURL=loader-fetcher.cjs.development.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader-fetcher.cjs.development.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '10';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`\n );\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n const global = globalThis as GlobalWithBundles;\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n const global = globalThis as GlobalWithBundles;\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\n"],"names":["VERSION","isBrowser","window","document","Api","constructor","opts","host","fetchLoaderData","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","message","statusText","json","text","JSON","parse","err","fetchHtmlData","component","embedHydrate","hydrate","makeAuthHeaders","makePostHeaders","tokens","projects","p","id","token","join","PlasmicModulesFetcher","undefined","api","fetchAllData","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","version","set","name","global","globalThis","__PLASMIC_BUNDLES","getBundleKey","internal_getCachedBundleInNodeServer","stringify"],"mappings":";;;;;;;;AA0HA,MAAMA,OAAO,GAAG,IAAI;AAEb,MAAMC,SAAS,GACpB,OAAOC,MAAM,KAAK,WAAW,IAC7BA,MAAM,IAAI,IAAI,IACd,OAAOA,MAAM,CAACC,QAAQ,KAAK,WAAW;MAE3BC,GAAG;EAEdC,YACUC,IAGP;;IAHO,SAAI,GAAJA,IAAI;IAKZ,IAAI,CAACC,IAAI,iBAAGD,IAAI,CAACC,IAAI,yBAAI,6BAA6B;;EAGxD,MAAMC,eAAe,CACnBC,UAAoB,EACpBH,IAKC;IAED,MAAM;MAAEI,QAAQ;MAAEC;KAAS,GAAGL,IAAI;IAClC,MAAMM,KAAK,GAAG,IAAIC,eAAe,CAAC,CAChC,CAAC,UAAU,EAAEH,QAAQ,WAARA,QAAQ,GAAI,OAAO,CAAC,EACjC,GAAGD,UAAU,CAACK,GAAG,CAAEC,SAAS,IAAK,CAAC,WAAW,EAAEA,SAAS,CAAC,CAAC,EAC1D,IAAIT,IAAI,CAACU,WAAW,GAAG,CAAC,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EACtD,IAAIV,IAAI,CAACW,aAAa,GAAG,CAAC,CAAC,eAAe,EAAEX,IAAI,CAACW,aAAa,CAAC,CAAC,GA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IAC9C,IAAID,MAAM,CAACE,iBAAiB,KAAKnB,SAAS,EAAE;MAC1CiB,MAAM,CAACE,iBAAiB,GAAG,EAAE;;IAE/BF,MAAM,CAACE,iBAAiB,CAACC,YAAY,CAAC,IAAI,CAAC/D,IAAI,CAAC,CAAC,GAAG8C,MAAM;;;AAI9D,SAAgBkB,oCAAoC,CAClDhE,IAAoB;;EAEpB,IAAIL,SAAS,EAAE;IACb,MAAM,IAAI2B,KAAK,wDAAwD,CAAC;;EAG1E,MAAMsC,MAAM,GAAGC,UAA+B;EAC9C,gCAAOD,MAAM,CAACE,iBAAiB,qBAAxB,sBAA2BC,YAAY,CAAC/D,IAAI,CAAC,CAAC;AACvD;AAEA,SAAS+D,YAAY,CAAC;EACpB9D,IAAI;EACJG,QAAQ;EACRO,aAAa;EACbN,OAAO;EACPgC;CACe;EACf,OAAOV,IAAI,CAACsC,SAAS,CAAC;IACpBhE,IAAI;IACJG,QAAQ;IACRO,aAAa;IACbN,OAAO;IACPgC;GACD,CAAC;AACJ;;;;;;"}
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=(e=require("@plasmicapp/isomorphic-unfetch"))&&"object"==typeof e&&"default"in e?e.default:e;const s="undefined"!=typeof window&&null!=window&&void 0!==window.document;class r{constructor(e){var t;this.opts=e,this.host=null!=(t=e.host)?t:"https://codegen.plasmic.app"}async fetchLoaderData(e,s){const{platform:r,preview:o}=s,a=new URLSearchParams([["platform",null!=r?r:"react"],...e.map(e=>["projectId",e]),...s.browserOnly?[["browserOnly","true"]]:[],...s.i18nKeyScheme?[["i18nKeyScheme",s.i18nKeyScheme]]:[]]).toString(),i=`${this.host}/api/v1/loader/code/${o?"preview":"published"}?${a}`,n=await t(i,{method:"GET",headers:this.makeGetHeaders()});if(n.status>=400){var c,h;const e=await this.parseJsonResponse(n);throw new Error("Error fetching loader data: "+(null!=(c=null==e||null==(h=e.error)?void 0:h.message)?c:n.statusText))}return await this.parseJsonResponse(n)}async parseJsonResponse(e){const t=await e.text();try{return JSON.parse(t)}catch(s){throw new Error(`Error parsing JSON response: ${s}; status: ${e.status}; response: ${t}`)}}async fetchHtmlData(e){const{projectId:s,component:r,embedHydrate:o,hydrate:a}=e,i=new URLSearchParams([["projectId",s],["component",r],["embedHydrate",o?"1":"0"],["hydrate",a?"1":"0"]]).toString(),n=await t(`${this.host}/api/v1/loader/html?${i}`,{method:"GET",headers:this.makeGetHeaders()});return await n.json()}makeGetHeaders(){return{"x-plasmic-loader-version":"10",...this.makeAuthHeaders()}}makePostHeaders(){return{"x-plasmic-loader-version":"10","Content-Type":"application/json",...this.makeAuthHeaders()}}makeAuthHeaders(){return{"x-plasmic-api-project-tokens":this.opts.projects.map(e=>`${e.id}:${e.token}`).join(",")}}}function o({host:e,platform:t,i18nKeyScheme:s,preview:r,projects:o}){return JSON.stringify({host:e,platform:t,i18nKeyScheme:s,preview:r,projects:o})}exports.Api=r,exports.PlasmicModulesFetcher=class{constructor(e){this.opts=e,this.curFetch=void 0,this.api=new r({projects:e.projects,host:e.host})}async fetchAllData(){const e=await this.getCachedOrFetch();return this.cacheBundleInNodeServer(e),e}async getCachedOrFetch(){if(this.opts.cache){const e=await this.opts.cache.get();if(e)return e}if(this.curFetch)return await this.curFetch;console.debug("Plasmic: doing a fresh fetch..."),this.curFetch=this.doFetch();const e=await this.curFetch;return this.curFetch=void 0,e}async doFetch(){const e=await this.api.fetchLoaderData(this.opts.projects.map(e=>e.version?`${e.id}@${e.version}`:e.id),{platform:this.opts.platform,preview:this.opts.preview,i18nKeyScheme:this.opts.i18nKeyScheme,browserOnly:s});return this.opts.cache&&await this.opts.cache.set(e),console.debug("Plasmic: fetched designs for "+e.projects.map(e=>`"${e.name}" (${e.id}@${e.version})`).join(", ")),e}cacheBundleInNodeServer(e){if(s)return;const t=globalThis;void 0===t.__PLASMIC_BUNDLES&&(t.__PLASMIC_BUNDLES={}),t.__PLASMIC_BUNDLES[o(this.opts)]=e}},exports.internal_getCachedBundleInNodeServer=function(e){var t;if(s)throw new Error("Should not be consulting Node server cache in browser");return null==(t=globalThis.__PLASMIC_BUNDLES)?void 0:t[o(e)]};
2
- //# sourceMappingURL=loader-fetcher.cjs.production.min.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader-fetcher.cjs.production.min.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '10';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`\n );\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n const global = globalThis as GlobalWithBundles;\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n const global = globalThis as GlobalWithBundles;\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\n"],"names":["isBrowser","window","document","Api","constructor","opts","this","host","[object Object]","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","_error$error","message","statusText","text","JSON","parse","err","component","embedHydrate","hydrate","json","x-plasmic-loader-version","makeAuthHeaders","makePostHeaders","Content-Type","x-plasmic-api-project-tokens","projects","p","id","token","join","getBundleKey","stringify","undefined","api","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","fetchLoaderData","version","set","name","global","globalThis","__PLASMIC_BUNDLES","_global$__PLASMIC_BUN"],"mappings":"yKA0HA,MAEaA,EACO,oBAAXC,QACG,MAAVA,aAC2B,IAApBA,OAAOC,eAEHC,EAEXC,YACUC,SAAAC,UAAAD,EAKRC,KAAKC,cAAOF,EAAKE,QAAQ,8BAG3BC,sBACEC,EACAJ,GAOA,MAAMK,SAAEA,EAAQC,QAAEA,GAAYN,EACxBO,EAAQ,IAAIC,gBAAgB,CAChC,CAAC,iBAAYH,EAAAA,EAAY,YACtBD,EAAWK,IAAKC,GAAc,CAAC,YAAaA,OAC3CV,EAAKW,YAAc,CAAC,CAAC,cAAe,SAAW,MAC/CX,EAAKY,cAAgB,CAAC,CAAC,gBAAiBZ,EAAKY,gBAAkB,KAClEC,WAEGC,KAASb,KAAKC,2BAClBI,EAAU,UAAY,eACpBC,IACEQ,QAAaC,EAAMF,EAAK,CAC5BG,OAAQ,MACRC,QAASjB,KAAKkB,mBAEhB,GAAIJ,EAAKK,QAAU,IAAK,CAAA,QACtB,MAAMC,QAAcpB,KAAKqB,kBAAkBP,GAC3C,MAAM,IAAIQ,qDAENF,YAAAA,EAAOA,cAAPG,EAAcC,WAAWV,EAAKW,aAKpC,aADmBzB,KAAKqB,kBAAkBP,GAIpCZ,wBAAwBY,GAC9B,MAAMY,QAAaZ,EAAKY,OACxB,IACE,OAAOC,KAAKC,MAAMF,GAClB,MAAOG,GACP,MAAM,IAAIP,sCACwBO,cAAgBf,EAAKK,qBAAqBO,MAKhFxB,oBAAoBH,GAMlB,MAAMU,U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Aa1D,KAAK+C,IAAIY,gBAC1B3D,KAAKD,KAAKwC,SAAS/B,IAAKgC,GACtBA,EAAEoB,WAAapB,EAAEC,MAAMD,EAAEoB,UAAYpB,EAAEC,IAEzC,CACErC,SAAUJ,KAAKD,KAAKK,SACpBC,QAASL,KAAKD,KAAKM,QACnBM,cAAeX,KAAKD,KAAKY,cACzBD,YAAahB,IAWjB,OARIM,KAAKD,KAAKoD,aACNnD,KAAKD,KAAKoD,MAAMU,IAAIH,GAE5BH,QAAQC,sCAC0BE,EAAKnB,SAClC/B,IAAKgC,OAAUA,EAAEsB,UAAUtB,EAAEC,MAAMD,EAAEoB,YACrCjB,KAAK,OAEHe,EAGDR,wBAAwBF,GAC9B,GAAItD,EACF,OAGF,MAAMqE,EAASC,gBACkBlB,IAA7BiB,EAAOE,oBACTF,EAAOE,kBAAoB,IAE7BF,EAAOE,kBAAkBrB,EAAa5C,KAAKD,OAASiD,0DAKtDjD,SAEA,GAAIL,EACF,MAAM,IAAI4B,+DAIZ,gBADe0C,WACDC,0BAAPC,EAA2BtB,EAAa7C"}
@@ -1,161 +0,0 @@
1
- import fetch from '@plasmicapp/isomorphic-unfetch';
2
-
3
- const VERSION = '10';
4
- const isBrowser = typeof window !== 'undefined' && window != null && typeof window.document !== 'undefined';
5
- class Api {
6
- constructor(opts) {
7
- var _opts$host;
8
- this.opts = opts;
9
- this.host = (_opts$host = opts.host) != null ? _opts$host : 'https://codegen.plasmic.app';
10
- }
11
- async fetchLoaderData(projectIds, opts) {
12
- const {
13
- platform,
14
- preview
15
- } = opts;
16
- const query = new URLSearchParams([['platform', platform != null ? platform : 'react'], ...projectIds.map(projectId => ['projectId', projectId]), ...(opts.browserOnly ? [['browserOnly', 'true']] : []), ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : [])]).toString();
17
- const url = `${this.host}/api/v1/loader/code/${preview ? 'preview' : 'published'}?${query}`;
18
- const resp = await fetch(url, {
19
- method: 'GET',
20
- headers: this.makeGetHeaders()
21
- });
22
- if (resp.status >= 400) {
23
- var _error$error$message, _error$error;
24
- const error = await this.parseJsonResponse(resp);
25
- throw new Error(`Error fetching loader data: ${(_error$error$message = error == null ? void 0 : (_error$error = error.error) == null ? void 0 : _error$error.message) != null ? _error$error$message : resp.statusText}`);
26
- }
27
- const json = await this.parseJsonResponse(resp);
28
- return json;
29
- }
30
- async parseJsonResponse(resp) {
31
- const text = await resp.text();
32
- try {
33
- return JSON.parse(text);
34
- } catch (err) {
35
- throw new Error(`Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`);
36
- }
37
- }
38
- async fetchHtmlData(opts) {
39
- const {
40
- projectId,
41
- component,
42
- embedHydrate,
43
- hydrate
44
- } = opts;
45
- const query = new URLSearchParams([['projectId', projectId], ['component', component], ['embedHydrate', embedHydrate ? '1' : '0'], ['hydrate', hydrate ? '1' : '0']]).toString();
46
- const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {
47
- method: 'GET',
48
- headers: this.makeGetHeaders()
49
- });
50
- const json = await resp.json();
51
- return json;
52
- }
53
- makeGetHeaders() {
54
- return {
55
- 'x-plasmic-loader-version': VERSION,
56
- ...this.makeAuthHeaders()
57
- };
58
- }
59
- // @ts-ignore
60
- makePostHeaders() {
61
- return {
62
- 'x-plasmic-loader-version': VERSION,
63
- 'Content-Type': 'application/json',
64
- ...this.makeAuthHeaders()
65
- };
66
- }
67
- makeAuthHeaders() {
68
- const tokens = this.opts.projects.map(p => `${p.id}:${p.token}`).join(',');
69
- return {
70
- 'x-plasmic-api-project-tokens': tokens
71
- };
72
- }
73
- }
74
-
75
- class PlasmicModulesFetcher {
76
- constructor(opts) {
77
- this.opts = opts;
78
- this.curFetch = undefined;
79
- this.api = new Api({
80
- projects: opts.projects,
81
- host: opts.host
82
- });
83
- }
84
- async fetchAllData() {
85
- // getCachedOrFetched uses a cache defined by the user.
86
- const bundle = await this.getCachedOrFetch();
87
- // For React Server Components (Next.js 13+),
88
- // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.
89
- // We don't want to pass them via normal page props because that will be serialized to the browser.
90
- // Instead, we pass the bundle (including the server modules) via the Node `global` variable.
91
- //
92
- // cacheBundleInNodeServer caches a bundle in the Node server process.
93
- this.cacheBundleInNodeServer(bundle);
94
- return bundle;
95
- }
96
- async getCachedOrFetch() {
97
- if (this.opts.cache) {
98
- const cachedData = await this.opts.cache.get();
99
- if (cachedData) {
100
- return cachedData;
101
- }
102
- }
103
- if (this.curFetch) {
104
- return await this.curFetch;
105
- }
106
- console.debug('Plasmic: doing a fresh fetch...');
107
- this.curFetch = this.doFetch();
108
- const data = await this.curFetch;
109
- this.curFetch = undefined;
110
- return data;
111
- }
112
- async doFetch() {
113
- const data = await this.api.fetchLoaderData(this.opts.projects.map(p => p.version ? `${p.id}@${p.version}` : p.id), {
114
- platform: this.opts.platform,
115
- preview: this.opts.preview,
116
- i18nKeyScheme: this.opts.i18nKeyScheme,
117
- browserOnly: isBrowser
118
- });
119
- if (this.opts.cache) {
120
- await this.opts.cache.set(data);
121
- }
122
- console.debug(`Plasmic: fetched designs for ${data.projects.map(p => `"${p.name}" (${p.id}@${p.version})`).join(', ')}`);
123
- return data;
124
- }
125
- cacheBundleInNodeServer(bundle) {
126
- if (isBrowser) {
127
- return;
128
- }
129
- const global = globalThis;
130
- if (global.__PLASMIC_BUNDLES === undefined) {
131
- global.__PLASMIC_BUNDLES = {};
132
- }
133
- global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;
134
- }
135
- }
136
- function internal_getCachedBundleInNodeServer(opts) {
137
- var _global$__PLASMIC_BUN;
138
- if (isBrowser) {
139
- throw new Error(`Should not be consulting Node server cache in browser`);
140
- }
141
- const global = globalThis;
142
- return (_global$__PLASMIC_BUN = global.__PLASMIC_BUNDLES) == null ? void 0 : _global$__PLASMIC_BUN[getBundleKey(opts)];
143
- }
144
- function getBundleKey({
145
- host,
146
- platform,
147
- i18nKeyScheme,
148
- preview,
149
- projects
150
- }) {
151
- return JSON.stringify({
152
- host,
153
- platform,
154
- i18nKeyScheme,
155
- preview,
156
- projects
157
- });
158
- }
159
-
160
- export { Api, PlasmicModulesFetcher, internal_getCachedBundleInNodeServer };
161
- //# sourceMappingURL=loader-fetcher.esm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader-fetcher.esm.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '10';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`\n );\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n const global = globalThis as GlobalWithBundles;\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n const global = globalThis as GlobalWithBundles;\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\n"],"names":["VERSION","isBrowser","window","document","Api","constructor","opts","host","fetchLoaderData","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","message","statusText","json","text","JSON","parse","err","fetchHtmlData","component","embedHydrate","hydrate","makeAuthHeaders","makePostHeaders","tokens","projects","p","id","token","join","PlasmicModulesFetcher","undefined","api","fetchAllData","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","version","set","name","global","globalThis","__PLASMIC_BUNDLES","getBundleKey","internal_getCachedBundleInNodeServer","stringify"],"mappings":";;AA0HA,MAAMA,OAAO,GAAG,IAAI;AAEb,MAAMC,SAAS,GACpB,OAAOC,MAAM,KAAK,WAAW,IAC7BA,MAAM,IAAI,IAAI,IACd,OAAOA,MAAM,CAACC,QAAQ,KAAK,WAAW;MAE3BC,GAAG;EAEdC,YACUC,IAGP;;IAHO,SAAI,GAAJA,IAAI;IAKZ,IAAI,CAACC,IAAI,iBAAGD,IAAI,CAACC,IAAI,yBAAI,6BAA6B;;EAGxD,MAAMC,eAAe,CACnBC,UAAoB,EACpBH,IAKC;IAED,MAAM;MAAEI,QAAQ;MAAEC;KAAS,GAAGL,IAAI;IAClC,MAAMM,KAAK,GAAG,IAAIC,eAAe,CAAC,CAChC,CAAC,UAAU,EAAEH,QAAQ,WAARA,QAAQ,GAAI,OAAO,CAAC,EACjC,GAAGD,UAAU,CAACK,GAAG,CAAEC,SAAS,IAAK,CAAC,WAAW,EAAEA,SAAS,CAAC,CAAC,EAC1D,IAAIT,IAAI,CAACU,WAAW,GAAG,CAAC,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EACtD,IAAIV,IAAI,CAACW,aAAa,GAAG,CAAC,CAAC,eAAe,EAAEX,IAAI,CAACW,aAAa,CAAC,CAAC,GAAG,EAAE,CAAC,CACvE,CAAC,CAACC,QAAQ,EAAE;IAEb,MAAMC,GAAG,MAAM,IAAI,CAACZ,2BAClBI,OAAO,GAAG,SAAS,GAAG,eACpBC,OAA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