@daouy/loader-react 1.0.409

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1567 @@
1
+ "use client";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
+ var __objRest = (source, exclude) => {
22
+ var target = {};
23
+ for (var prop in source)
24
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
25
+ target[prop] = source[prop];
26
+ if (source != null && __getOwnPropSymbols)
27
+ for (var prop of __getOwnPropSymbols(source)) {
28
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
29
+ target[prop] = source[prop];
30
+ }
31
+ return target;
32
+ };
33
+ var __async = (__this, __arguments, generator) => {
34
+ return new Promise((resolve, reject) => {
35
+ var fulfilled = (value) => {
36
+ try {
37
+ step(generator.next(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var rejected = (value) => {
43
+ try {
44
+ step(generator.throw(value));
45
+ } catch (e) {
46
+ reject(e);
47
+ }
48
+ };
49
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
50
+ step((generator = generator.apply(__this, __arguments)).next());
51
+ });
52
+ };
53
+
54
+ // src/loader-client.ts
55
+ import * as DaouyDataSourcesContext from "@daouy/data-sources-context";
56
+ import * as DaouyHost from "@daouy/host";
57
+ import {
58
+ registerComponent,
59
+ registerFunction,
60
+ registerGlobalContext,
61
+ registerToken,
62
+ registerTrait,
63
+ stateHelpersKeys
64
+ } from "@daouy/host";
65
+ import { DaouyModulesFetcher as DaouyModulesFetcher2 } from "@daouy/loader-core";
66
+ import * as DaouyQuery from "@daouy/query";
67
+ import React3 from "react";
68
+ import ReactDOM from "react-dom";
69
+ import * as jsxDevRuntime from "react/jsx-dev-runtime";
70
+ import * as jsxRuntime from "react/jsx-runtime";
71
+
72
+ // src/PlasmicRootProvider.tsx
73
+ import { PageParamsProvider } from "@daouy/host";
74
+ import { DaouyQueryDataProvider } from "@daouy/query";
75
+ import * as React2 from "react";
76
+
77
+ // src/utils.tsx
78
+ import pascalcase from "pascalcase";
79
+ import * as React from "react";
80
+ var isBrowser = typeof window !== "undefined";
81
+ function useForceUpdate() {
82
+ const [, setTick] = React.useState(0);
83
+ const update = React.useCallback(() => {
84
+ setTick((tick) => tick + 1);
85
+ }, []);
86
+ return update;
87
+ }
88
+ function useStableLookupSpec(spec) {
89
+ return useStableLookupSpecs(spec)[0];
90
+ }
91
+ function useStableLookupSpecs(...specs) {
92
+ const [stableSpecs, setStableSpecs] = React.useState(specs);
93
+ React.useEffect(() => {
94
+ if (specs.length !== stableSpecs.length || specs.some((s, i) => !areLookupSpecsEqual(s, stableSpecs[i]))) {
95
+ setStableSpecs(specs);
96
+ }
97
+ }, [specs, stableSpecs]);
98
+ return stableSpecs;
99
+ }
100
+ function areLookupSpecsEqual(spec1, spec2) {
101
+ if (spec1 === spec2) {
102
+ return true;
103
+ }
104
+ if (typeof spec1 !== typeof spec2) {
105
+ return false;
106
+ }
107
+ const fullSpec1 = toFullLookup(spec1);
108
+ const fullSpec2 = toFullLookup(spec2);
109
+ return (isNameSpec(fullSpec1) && isNameSpec(fullSpec2) && fullSpec1.name === fullSpec2.name && fullSpec1.isCode === fullSpec2.isCode || isPathSpec(fullSpec1) && isPathSpec(fullSpec2) && fullSpec1.path === fullSpec2.path) && fullSpec1.projectId === fullSpec2.projectId;
110
+ }
111
+ function isNameSpec(lookup) {
112
+ return "name" in lookup;
113
+ }
114
+ function isPathSpec(lookup) {
115
+ return "path" in lookup;
116
+ }
117
+ function toFullLookup(lookup) {
118
+ const namePart = typeof lookup === "string" ? lookup : lookup.name;
119
+ const projectId = typeof lookup === "string" ? void 0 : lookup.projectId;
120
+ const codeComponent = typeof lookup === "string" ? void 0 : lookup.isCode;
121
+ if (codeComponent !== true && namePart.startsWith("/")) {
122
+ return { path: normalizePath(namePart), projectId };
123
+ } else {
124
+ return {
125
+ name: codeComponent ? namePart : normalizeName(namePart),
126
+ rawName: namePart.trim(),
127
+ projectId,
128
+ isCode: codeComponent
129
+ };
130
+ }
131
+ }
132
+ function normalizePath(path) {
133
+ return path.trim();
134
+ }
135
+ function normalizeName(name) {
136
+ return pascalcase(name).trim();
137
+ }
138
+ function useIsMounted() {
139
+ const ref = React.useRef(false);
140
+ const isMounted = React.useCallback(() => ref.current, []);
141
+ React.useEffect(() => {
142
+ ref.current = true;
143
+ return () => {
144
+ ref.current = false;
145
+ };
146
+ }, []);
147
+ return isMounted;
148
+ }
149
+ function matchesPagePath(pattern, path) {
150
+ const normalizedPattern = "/" + pattern.replace(/^\/|\/$/g, "");
151
+ const normalizedPath = "/" + path.replace(/^\/|\/$/g, "");
152
+ const regexString = normalizedPattern.replace(/\/\[\[\.\.\.([^\]^]+)]]/g, "(?:/([^]*))?").replace(/\/\[\.\.\.([^\]^]+)]/g, "/([^]*)").replace(/\[([^\]^]+)]/g, "([^/]+)").replace(/\//g, "\\/");
153
+ const regex = new RegExp(`^/?${regexString}$`);
154
+ const match = normalizedPath.match(regex);
155
+ if (!match)
156
+ return false;
157
+ const slugNames = [...pattern.matchAll(/\[\.?\.?\.?([^[\]]+)]/g)].map(
158
+ (m) => m[1]
159
+ );
160
+ const params = {};
161
+ for (let i = 0; i < slugNames.length; i++) {
162
+ const slugName = slugNames[i];
163
+ const value = match[i + 1];
164
+ if (pattern.includes(`[[...${slugName}]]`)) {
165
+ params[slugName] = value ? value.split("/").filter(Boolean) : [];
166
+ } else if (pattern.includes(`[...${slugName}]`)) {
167
+ params[slugName] = value.split("/").filter(Boolean);
168
+ } else if (value !== void 0) {
169
+ params[slugName] = value;
170
+ }
171
+ }
172
+ return { params };
173
+ }
174
+ function isDynamicPagePath(path) {
175
+ return !!path.match(/\[[^/]*\]/);
176
+ }
177
+ function matchesCompMeta(lookup, meta) {
178
+ if (lookup.projectId && meta.projectId !== lookup.projectId) {
179
+ return false;
180
+ }
181
+ return isNameSpec(lookup) ? (lookup.name === meta.name || lookup.rawName === meta.name || lookup.rawName === meta.displayName) && (lookup.isCode == null || lookup.isCode === meta.isCode) : !!(meta.path && matchesPagePath(meta.path, lookup.path));
182
+ }
183
+ function getCompMetas(metas, lookup) {
184
+ const full = toFullLookup(lookup);
185
+ return metas.filter((meta) => matchesCompMeta(full, meta)).map(
186
+ (meta) => {
187
+ if (isNameSpec(full) || !meta.path) {
188
+ return meta;
189
+ }
190
+ const match = matchesPagePath(meta.path, full.path);
191
+ if (!match) {
192
+ return meta;
193
+ }
194
+ return __spreadProps(__spreadValues({}, meta), { params: match.params });
195
+ }
196
+ ).sort(
197
+ (meta1, meta2) => (
198
+ // We sort the matched component metas by the number of path params, so
199
+ // if there are two pages `/products/foo` and `/products/[slug]`,
200
+ // the first one will have higher precedence.
201
+ Array.from(Object.keys(meta1.params || {})).length - Array.from(Object.keys(meta2.params || {})).length
202
+ )
203
+ );
204
+ }
205
+ function getLookupSpecName(lookup) {
206
+ if (typeof lookup === "string") {
207
+ return lookup;
208
+ } else if (lookup.projectId) {
209
+ return `${lookup.name} (project ${lookup.projectId})`;
210
+ } else {
211
+ return lookup.name;
212
+ }
213
+ }
214
+ function MaybeWrap(props) {
215
+ return props.cond ? props.wrapper(props.children) : props.children;
216
+ }
217
+ function uniq(elements) {
218
+ return Array.from(new Set(elements));
219
+ }
220
+ function intersect(a, b) {
221
+ const setB = new Set(b);
222
+ return a.filter((elt) => setB.has(elt));
223
+ }
224
+
225
+ // src/variation.ts
226
+ function getDaouyCookieValues() {
227
+ return Object.fromEntries(
228
+ document.cookie.split("; ").filter((cookie) => cookie.includes("daouy:")).map((cookie) => cookie.split("=")).map(([key, value]) => [key.split(":")[1], value])
229
+ );
230
+ }
231
+ function updateDaouyCookieValue(key, value) {
232
+ document.cookie = `daouy:${key}=${value}`;
233
+ }
234
+ var getGlobalVariantsFromSplits = (splits, variation) => {
235
+ const globalVariants = [];
236
+ Object.keys(variation).map((variationKey) => {
237
+ const [_type, splitId] = variationKey.split(".");
238
+ const sliceId = variation[variationKey];
239
+ const split = splits.find(
240
+ (s) => s.id === splitId || s.externalId === splitId
241
+ );
242
+ if (split) {
243
+ const slice = split.slices.find((s) => s.id === sliceId || s.externalId === sliceId);
244
+ if (slice) {
245
+ slice.contents.map((x) => {
246
+ globalVariants.push({
247
+ name: x.group,
248
+ value: x.variant,
249
+ projectId: x.projectId
250
+ });
251
+ });
252
+ }
253
+ }
254
+ });
255
+ return globalVariants;
256
+ };
257
+ var mergeGlobalVariantsSpec = (target, from) => {
258
+ let result = [...target];
259
+ const existingGlobalVariants = new Set(
260
+ target.map((t) => {
261
+ var _a;
262
+ return `${t.name}-${(_a = t.projectId) != null ? _a : ""}`;
263
+ })
264
+ );
265
+ const newGlobals = from.filter(
266
+ (t) => {
267
+ var _a;
268
+ return !existingGlobalVariants.has(`${t.name}-${(_a = t.projectId) != null ? _a : ""}`);
269
+ }
270
+ );
271
+ if (newGlobals.length > 0) {
272
+ result = [...result, ...newGlobals];
273
+ }
274
+ return result;
275
+ };
276
+
277
+ // src/PlasmicRootProvider.tsx
278
+ var DaouyRootContext = React2.createContext(void 0);
279
+ function DaouyRootProvider(props) {
280
+ const {
281
+ globalVariants,
282
+ prefetchedData,
283
+ children,
284
+ skipCss,
285
+ skipFonts,
286
+ prefetchedQueryData,
287
+ suspenseForQueryData,
288
+ globalContextsProps,
289
+ variation,
290
+ translator,
291
+ Head,
292
+ Link,
293
+ pageRoute,
294
+ pageParams,
295
+ pageQuery,
296
+ suspenseFallback,
297
+ disableLoadingBoundary,
298
+ disableRootLoadingBoundary,
299
+ styleTokenOverridesProjectId
300
+ } = props;
301
+ const loader = props.loader.__internal;
302
+ if (prefetchedData) {
303
+ loader.registerPrefetchedBundle(prefetchedData.bundle);
304
+ }
305
+ const [splits, setSplits] = React2.useState(loader.getActiveSplits());
306
+ const forceUpdate = useForceUpdate();
307
+ const watcher = React2.useMemo(
308
+ () => ({
309
+ onDataFetched: () => {
310
+ setSplits(loader.getActiveSplits());
311
+ forceUpdate();
312
+ }
313
+ }),
314
+ [loader, forceUpdate]
315
+ );
316
+ React2.useEffect(() => {
317
+ loader.subscribeDaouyRoot(watcher);
318
+ return () => loader.unsubscribeDaouyRoot(watcher);
319
+ }, [watcher, loader]);
320
+ const currentContextValue = React2.useContext(DaouyRootContext);
321
+ const { user, userAuthToken, isUserLoading, authRedirectUri } = props;
322
+ const value = React2.useMemo(() => {
323
+ var _a, _b, _c;
324
+ const withCurrentContextValueFallback = (v, key) => {
325
+ return v !== void 0 ? v : currentContextValue == null ? void 0 : currentContextValue[key];
326
+ };
327
+ return {
328
+ globalVariants: [
329
+ ...mergeGlobalVariantsSpec(
330
+ globalVariants != null ? globalVariants : [],
331
+ getGlobalVariantsFromSplits(splits, variation != null ? variation : {})
332
+ ),
333
+ ...(_a = currentContextValue == null ? void 0 : currentContextValue.globalVariants) != null ? _a : []
334
+ ],
335
+ globalContextsProps: __spreadValues(__spreadValues({}, (_b = currentContextValue == null ? void 0 : currentContextValue.globalContextsProps) != null ? _b : {}), globalContextsProps != null ? globalContextsProps : {}),
336
+ loader: withCurrentContextValueFallback(loader, "loader"),
337
+ variation: __spreadValues(__spreadValues({}, (_c = currentContextValue == null ? void 0 : currentContextValue.variation) != null ? _c : {}), variation != null ? variation : {}),
338
+ translator: withCurrentContextValueFallback(translator, "translator"),
339
+ Head: withCurrentContextValueFallback(Head, "Head"),
340
+ Link: withCurrentContextValueFallback(Link, "Link"),
341
+ user: withCurrentContextValueFallback(user, "user"),
342
+ userAuthToken: withCurrentContextValueFallback(
343
+ userAuthToken,
344
+ "userAuthToken"
345
+ ),
346
+ isUserLoading: withCurrentContextValueFallback(
347
+ isUserLoading,
348
+ "isUserLoading"
349
+ ),
350
+ authRedirectUri: withCurrentContextValueFallback(
351
+ authRedirectUri,
352
+ "authRedirectUri"
353
+ ),
354
+ suspenseFallback: withCurrentContextValueFallback(
355
+ suspenseFallback,
356
+ "suspenseFallback"
357
+ ),
358
+ disableLoadingBoundary: withCurrentContextValueFallback(
359
+ disableLoadingBoundary,
360
+ "disableLoadingBoundary"
361
+ ),
362
+ styleTokenOverridesProjectId
363
+ };
364
+ }, [
365
+ globalVariants,
366
+ variation,
367
+ globalContextsProps,
368
+ loader,
369
+ splits,
370
+ translator,
371
+ Head,
372
+ Link,
373
+ user,
374
+ userAuthToken,
375
+ isUserLoading,
376
+ authRedirectUri,
377
+ suspenseFallback,
378
+ disableLoadingBoundary,
379
+ styleTokenOverridesProjectId,
380
+ currentContextValue
381
+ ]);
382
+ React2.useEffect(() => {
383
+ loader.trackRender({
384
+ renderCtx: {
385
+ // We track the provider as a single entity
386
+ rootComponentId: "provider",
387
+ teamIds: loader.getTeamIds(),
388
+ projectIds: loader.getProjectIds()
389
+ },
390
+ variation: value.variation
391
+ });
392
+ }, [loader, value]);
393
+ const reactMajorVersion = +React2.version.split(".")[0];
394
+ const shouldDisableRootLoadingBoundary = disableRootLoadingBoundary != null ? disableRootLoadingBoundary : loader.getBundle().disableRootLoadingBoundaryByDefault;
395
+ return /* @__PURE__ */ React2.createElement(
396
+ DaouyQueryDataProvider,
397
+ {
398
+ prefetchedCache: prefetchedQueryData,
399
+ suspense: suspenseForQueryData
400
+ },
401
+ /* @__PURE__ */ React2.createElement(DaouyRootContext.Provider, { value }, !skipCss && /* @__PURE__ */ React2.createElement(
402
+ DaouyCss,
403
+ {
404
+ loader,
405
+ prefetchedData,
406
+ skipFonts
407
+ }
408
+ ), /* @__PURE__ */ React2.createElement(
409
+ PageParamsProvider,
410
+ {
411
+ route: pageRoute,
412
+ params: pageParams,
413
+ query: pageQuery
414
+ },
415
+ /* @__PURE__ */ React2.createElement(
416
+ MaybeWrap,
417
+ {
418
+ cond: !shouldDisableRootLoadingBoundary && reactMajorVersion >= 18,
419
+ wrapper: (contents) => /* @__PURE__ */ React2.createElement(React2.Suspense, { fallback: suspenseFallback != null ? suspenseFallback : "Loading..." }, contents)
420
+ },
421
+ children
422
+ )
423
+ ))
424
+ );
425
+ }
426
+ var DaouyCss = React2.memo(function DaouyCss2(props) {
427
+ const { loader, prefetchedData, skipFonts } = props;
428
+ const [useScopedCss, setUseScopedCss] = React2.useState(!!prefetchedData);
429
+ const builtCss = buildCss(loader, {
430
+ scopedCompMetas: useScopedCss && prefetchedData ? prefetchedData.bundle.components : void 0,
431
+ skipFonts
432
+ });
433
+ const forceUpdate = useForceUpdate();
434
+ const watcher = React2.useMemo(
435
+ () => ({
436
+ onDataFetched: () => {
437
+ setUseScopedCss(false);
438
+ forceUpdate();
439
+ }
440
+ }),
441
+ [loader, forceUpdate]
442
+ );
443
+ React2.useEffect(() => {
444
+ loader.subscribeDaouyRoot(watcher);
445
+ return () => loader.unsubscribeDaouyRoot(watcher);
446
+ }, [watcher, loader]);
447
+ return /* @__PURE__ */ React2.createElement("style", { dangerouslySetInnerHTML: { __html: builtCss } });
448
+ });
449
+ function buildCss(loader, opts) {
450
+ const { scopedCompMetas, skipFonts } = opts;
451
+ const cssFiles = scopedCompMetas && /* @__PURE__ */ new Set([
452
+ "entrypoint.css",
453
+ ...scopedCompMetas.map((c) => c.cssFile)
454
+ ]);
455
+ const cssModules = loader.getLookup().getCss().filter((f) => !cssFiles || cssFiles.has(f.fileName));
456
+ const getPri = (fileName) => fileName === "entrypoint.css" ? 0 : 1;
457
+ const compareModules = (a, b) => getPri(a.fileName) !== getPri(b.fileName) ? getPri(a.fileName) - getPri(b.fileName) : a.fileName.localeCompare(b.fileName);
458
+ cssModules.sort(compareModules);
459
+ const remoteFonts = loader.getLookup().getRemoteFonts();
460
+ return `
461
+ ${skipFonts ? "" : remoteFonts.map((f) => `@import url('${f.url}');`).join("\n")}
462
+ ${cssModules.map((mod) => mod.source).join("\n")}
463
+ `;
464
+ }
465
+ function useDaouyRootContext() {
466
+ return React2.useContext(DaouyRootContext);
467
+ }
468
+
469
+ // src/global-variants.ts
470
+ function createUseGlobalVariant(name, projectId) {
471
+ return () => {
472
+ var _a;
473
+ const rootContext = useDaouyRootContext();
474
+ if (!rootContext) {
475
+ return void 0;
476
+ }
477
+ const loader = rootContext.loader;
478
+ const spec = [
479
+ ...loader.getGlobalVariants(),
480
+ ...(_a = rootContext.globalVariants) != null ? _a : []
481
+ ].find(
482
+ (spec2) => spec2.name === name && (!spec2.projectId || spec2.projectId === projectId)
483
+ );
484
+ return spec ? spec.value : void 0;
485
+ };
486
+ }
487
+
488
+ // src/loader-shared.ts
489
+ import {
490
+ Registry
491
+ } from "@daouy/loader-core";
492
+ import {
493
+ internal_getCachedBundleInNodeServer
494
+ } from "@daouy/loader-fetcher";
495
+ import { getActiveVariation, getExternalIds } from "@daouy/loader-splits";
496
+
497
+ // src/bundles.ts
498
+ import {
499
+ getBundleSubset
500
+ } from "@daouy/loader-core";
501
+ function getUsedComps(allComponents, entryCompIds) {
502
+ const q = [...entryCompIds];
503
+ const seenIds = new Set(entryCompIds);
504
+ const componentMetaById = new Map(
505
+ allComponents.map((meta) => [meta.id, meta])
506
+ );
507
+ const usedComps = [];
508
+ while (q.length > 0) {
509
+ const [id] = q.splice(0, 1);
510
+ const meta = componentMetaById.get(id);
511
+ if (!meta) {
512
+ continue;
513
+ }
514
+ usedComps.push(meta);
515
+ meta.usedComponents.forEach((usedCompId) => {
516
+ if (!seenIds.has(usedCompId)) {
517
+ seenIds.add(usedCompId);
518
+ q.push(usedCompId);
519
+ }
520
+ });
521
+ }
522
+ return usedComps;
523
+ }
524
+ function prepComponentData(bundle, compMetas, opts) {
525
+ if (compMetas.length === 0) {
526
+ return {
527
+ entryCompMetas: bundle.components,
528
+ bundle,
529
+ remoteFontUrls: []
530
+ };
531
+ }
532
+ const usedComps = getUsedComps(
533
+ bundle.components,
534
+ compMetas.map((compMeta) => compMeta.id)
535
+ );
536
+ const compPaths = usedComps.map((compMeta) => compMeta.entry);
537
+ const subBundle = getBundleSubset(
538
+ bundle,
539
+ [
540
+ "entrypoint.css",
541
+ ...compPaths,
542
+ "root-provider.js",
543
+ ...bundle.projects.map((x) => x.styleTokensProviderFileName).filter((x) => !!x),
544
+ ...bundle.projects.map((x) => x.globalContextsProviderFileName).filter((x) => !!x),
545
+ // We need to explicitly include global context provider components
546
+ // to make sure they are kept in bundle.components. That's because
547
+ // for esbuild, just the globalContextsProviderFileName is not enough,
548
+ // because it will import a chunk that includes the global context
549
+ // component, instead of importing that global context component's
550
+ // entry file. And because nothing depends on the global context component's
551
+ // entry file, we end up excluding the global context component from
552
+ // bundle.components, which then makes its substitution not work.
553
+ // Instead, we forcibly include it here (we'll definitely need it anyway!).
554
+ ...bundle.components.filter((c) => c.isGlobalContextProvider).map((c) => c.entry),
555
+ ...bundle.globalGroups.map((g) => g.contextFile)
556
+ ],
557
+ opts
558
+ );
559
+ const remoteFontUrls = [];
560
+ subBundle.projects.forEach(
561
+ (p) => remoteFontUrls.push(...p.remoteFonts.map((f) => f.url))
562
+ );
563
+ return {
564
+ entryCompMetas: compMetas,
565
+ bundle: subBundle,
566
+ remoteFontUrls
567
+ };
568
+ }
569
+ function mergeBundles(target, from) {
570
+ var _a, _b, _c, _d, _e, _f, _g;
571
+ const existingProjects = new Set(target.projects.map((p) => p.id));
572
+ const newProjects = from.projects.filter((p) => !existingProjects.has(p.id));
573
+ if (newProjects.length > 0) {
574
+ target = __spreadProps(__spreadValues({}, target), {
575
+ projects: [...target.projects, ...newProjects]
576
+ });
577
+ }
578
+ const existingCompIds = new Set(target.components.map((c) => c.id));
579
+ function shouldIncludeComponentInBundle(c) {
580
+ var _a2;
581
+ if (existingCompIds.has(c.id)) {
582
+ return false;
583
+ }
584
+ if (!existingProjects.has(c.projectId)) {
585
+ return true;
586
+ }
587
+ const targetBundleFilteredIds = (_a2 = target.filteredIds[c.projectId]) != null ? _a2 : [];
588
+ return targetBundleFilteredIds.includes(c.id);
589
+ }
590
+ const newCompMetas = from.components.filter(
591
+ (m) => shouldIncludeComponentInBundle(m)
592
+ );
593
+ if (newCompMetas.length > 0) {
594
+ target = __spreadProps(__spreadValues({}, target), {
595
+ components: [...target.components, ...newCompMetas]
596
+ });
597
+ target.filteredIds = Object.fromEntries(
598
+ Object.entries(target.filteredIds).map(([k, v]) => [k, [...v]])
599
+ );
600
+ from.projects.forEach((fromProject) => {
601
+ var _a2, _b2;
602
+ const projectId = fromProject.id;
603
+ const fromBundleFilteredIds = (_a2 = from.filteredIds[projectId]) != null ? _a2 : [];
604
+ if (!existingProjects.has(projectId)) {
605
+ target.filteredIds[projectId] = [...fromBundleFilteredIds];
606
+ } else {
607
+ target.filteredIds[projectId] = intersect(
608
+ (_b2 = target.filteredIds[projectId]) != null ? _b2 : [],
609
+ fromBundleFilteredIds
610
+ );
611
+ }
612
+ });
613
+ }
614
+ const existingModules = {
615
+ browser: new Set(target.modules.browser.map((m) => m.fileName)),
616
+ server: new Set(target.modules.server.map((m) => m.fileName))
617
+ };
618
+ const newModules = {
619
+ browser: from.modules.browser.filter(
620
+ (m) => !existingModules.browser.has(m.fileName)
621
+ ),
622
+ server: from.modules.server.filter(
623
+ (m) => !existingModules.server.has(m.fileName)
624
+ )
625
+ };
626
+ if (newModules.browser.length > 0 || newModules.server.length > 0) {
627
+ target = __spreadProps(__spreadValues({}, target), {
628
+ modules: {
629
+ browser: [...target.modules.browser, ...newModules.browser],
630
+ server: [...target.modules.server, ...newModules.server]
631
+ }
632
+ });
633
+ }
634
+ const existingGlobalIds = new Set(target.globalGroups.map((g) => g.id));
635
+ const newGlobals = from.globalGroups.filter(
636
+ (g) => !existingGlobalIds.has(g.id)
637
+ );
638
+ if (newGlobals.length > 0) {
639
+ target = __spreadProps(__spreadValues({}, target), {
640
+ globalGroups: [...target.globalGroups, ...newGlobals]
641
+ });
642
+ }
643
+ const existingSplitIds = new Set(target.activeSplits.map((s) => s.id));
644
+ const newSplits = (_a = from.activeSplits.filter(
645
+ // Don't include splits belonging to projects already present
646
+ // in the target bundle
647
+ (s) => !existingSplitIds.has(s.id) && !existingProjects.has(s.projectId)
648
+ )) != null ? _a : [];
649
+ if (newSplits.length > 0) {
650
+ target = __spreadProps(__spreadValues({}, target), {
651
+ activeSplits: [...target.activeSplits, ...newSplits]
652
+ });
653
+ }
654
+ target.bundleKey = (_c = (_b = target.bundleKey) != null ? _b : from.bundleKey) != null ? _c : null;
655
+ target.deferChunksByDefault = (_e = (_d = target.deferChunksByDefault) != null ? _d : from.deferChunksByDefault) != null ? _e : false;
656
+ target.disableRootLoadingBoundaryByDefault = (_g = (_f = target.disableRootLoadingBoundaryByDefault) != null ? _f : from.disableRootLoadingBoundaryByDefault) != null ? _g : false;
657
+ return target;
658
+ }
659
+ var convertBundlesToComponentRenderData = (bundles, compMetas) => {
660
+ if (bundles.length === 0) {
661
+ return null;
662
+ }
663
+ const mergedBundles = bundles.reduce((prev, cur) => mergeBundles(prev, cur));
664
+ return prepComponentData(mergedBundles, compMetas);
665
+ };
666
+
667
+ // src/component-lookup.ts
668
+ function getFirstCompMeta(metas, lookup) {
669
+ const filtered = getCompMetas(metas, lookup);
670
+ return filtered.length === 0 ? void 0 : filtered[0];
671
+ }
672
+ var ComponentLookup = class {
673
+ constructor(bundle, registry) {
674
+ this.bundle = bundle;
675
+ this.registry = registry;
676
+ }
677
+ getComponentMeta(spec) {
678
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
679
+ return compMeta;
680
+ }
681
+ getComponent(spec, opts = {}) {
682
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
683
+ if (!compMeta) {
684
+ throw new Error(`Component not found: ${spec}`);
685
+ }
686
+ const moduleName = compMeta.entry;
687
+ if (!this.registry.hasModule(moduleName, opts)) {
688
+ throw new Error(`Component not yet fetched: ${compMeta.name}`);
689
+ }
690
+ const entry = this.registry.load(moduleName, {
691
+ forceOriginal: opts.forceOriginal
692
+ });
693
+ return !opts.forceOriginal && typeof (entry == null ? void 0 : entry.getDaouyComponent) === "function" ? entry.getDaouyComponent() : entry.default;
694
+ }
695
+ hasComponent(spec) {
696
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
697
+ if (compMeta) {
698
+ return this.registry.hasModule(compMeta.entry);
699
+ }
700
+ return false;
701
+ }
702
+ getGlobalContexts() {
703
+ const customGlobalMetas = this.bundle.globalGroups.filter(
704
+ (m) => m.type === "global-user-defined"
705
+ );
706
+ return customGlobalMetas.map((meta) => ({
707
+ meta,
708
+ context: this.registry.load(meta.contextFile).default
709
+ }));
710
+ }
711
+ /** Returns StyleTokensProvider if the project has style token overrides. */
712
+ maybeGetStyleTokensProvider(spec, styleTokenOverridesProjectId) {
713
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
714
+ let projectMeta;
715
+ if (styleTokenOverridesProjectId) {
716
+ projectMeta = this.bundle.projects.find(
717
+ (x) => x.id === styleTokenOverridesProjectId
718
+ );
719
+ if (!projectMeta) {
720
+ console.warn(
721
+ `styleTokenOverridesProjectId "${styleTokenOverridesProjectId}" not found. Defaulting to root component's project.`
722
+ );
723
+ }
724
+ }
725
+ if (!projectMeta && (compMeta == null ? void 0 : compMeta.projectId)) {
726
+ projectMeta = this.bundle.projects.find(
727
+ (x) => x.id === compMeta.projectId
728
+ );
729
+ }
730
+ if (!projectMeta || !projectMeta.styleTokensProviderFileName || !this.registry.hasModule(projectMeta.styleTokensProviderFileName) || !projectMeta.hasStyleTokenOverrides) {
731
+ return void 0;
732
+ }
733
+ const entry = this.registry.load(projectMeta.styleTokensProviderFileName);
734
+ return entry.StyleTokensProvider;
735
+ }
736
+ getGlobalContextsProvider(spec) {
737
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
738
+ const projectMeta = compMeta ? this.bundle.projects.find((x) => x.id === compMeta.projectId) : void 0;
739
+ if (!projectMeta || !projectMeta.globalContextsProviderFileName || !this.registry.hasModule(projectMeta.globalContextsProviderFileName)) {
740
+ return void 0;
741
+ }
742
+ const entry = this.registry.load(
743
+ projectMeta.globalContextsProviderFileName
744
+ );
745
+ return typeof (entry == null ? void 0 : entry.getDaouyComponent) === "function" ? entry.getDaouyComponent() : entry.default;
746
+ }
747
+ getRootProvider() {
748
+ const entry = this.registry.load("root-provider.js");
749
+ return entry.default;
750
+ }
751
+ getCss() {
752
+ return this.bundle.modules.browser.filter(
753
+ (mod) => mod.type === "asset" && mod.fileName.endsWith("css")
754
+ );
755
+ }
756
+ getRemoteFonts() {
757
+ return this.bundle.projects.flatMap((p) => p.remoteFonts);
758
+ }
759
+ };
760
+
761
+ // src/loader-shared.ts
762
+ var SUBSTITUTED_COMPONENTS = {};
763
+ var REGISTERED_CODE_COMPONENT_HELPERS = {};
764
+ var SUBSTITUTED_GLOBAL_VARIANT_HOOKS = {};
765
+ var REGISTERED_CUSTOM_FUNCTIONS = {};
766
+ function customFunctionImportAlias(meta) {
767
+ const customFunctionPrefix = `__fn_`;
768
+ return meta.namespace ? `${customFunctionPrefix}${meta.namespace}__${meta.name}` : `${customFunctionPrefix}${meta.name}`;
769
+ }
770
+ function internalSetRegisteredFunction(fn, meta) {
771
+ REGISTERED_CUSTOM_FUNCTIONS[customFunctionImportAlias(meta)] = fn;
772
+ }
773
+ function parseFetchComponentDataArgs(...args) {
774
+ let specs;
775
+ let opts;
776
+ if (Array.isArray(args[0])) {
777
+ specs = args[0];
778
+ opts = args[1];
779
+ } else {
780
+ specs = args;
781
+ opts = void 0;
782
+ }
783
+ return { specs, opts };
784
+ }
785
+ var BaseInternalDaouyComponentLoader = class {
786
+ constructor(args) {
787
+ this.registry = new Registry();
788
+ this.globalVariants = [];
789
+ this.subs = [];
790
+ this.bundle = {
791
+ modules: {
792
+ browser: [],
793
+ server: []
794
+ },
795
+ components: [],
796
+ globalGroups: [],
797
+ projects: [],
798
+ activeSplits: [],
799
+ bundleKey: null,
800
+ deferChunksByDefault: false,
801
+ disableRootLoadingBoundaryByDefault: false,
802
+ filteredIds: {}
803
+ };
804
+ this.opts = args.opts;
805
+ this.fetcher = args.fetcher;
806
+ this.onBundleMerged = args.onBundleMerged;
807
+ this.onBundleFetched = args.onBundleFetched;
808
+ this.registerModules(args.builtinModules);
809
+ }
810
+ maybeGetCompMetas(...specs) {
811
+ const found = /* @__PURE__ */ new Set();
812
+ const missing = [];
813
+ for (const spec of specs) {
814
+ const filteredMetas = getCompMetas(this.bundle.components, spec);
815
+ if (filteredMetas.length > 0) {
816
+ filteredMetas.forEach((meta) => found.add(meta));
817
+ } else {
818
+ missing.push(spec);
819
+ }
820
+ }
821
+ return { found: Array.from(found.keys()), missing };
822
+ }
823
+ maybeFetchComponentData(...args) {
824
+ return __async(this, null, function* () {
825
+ const { specs, opts } = parseFetchComponentDataArgs(...args);
826
+ const returnWithSpecsToFetch = (specsToFetch) => __async(this, null, function* () {
827
+ yield this.fetchMissingData({ missingSpecs: specsToFetch });
828
+ const { found: existingMetas2, missing: missingSpecs2 } = this.maybeGetCompMetas(...specs);
829
+ if (missingSpecs2.length > 0) {
830
+ return null;
831
+ }
832
+ return prepComponentData(this.bundle, existingMetas2, opts);
833
+ });
834
+ if (this.opts.alwaysFresh) {
835
+ return yield returnWithSpecsToFetch(specs);
836
+ }
837
+ const { found: existingMetas, missing: missingSpecs } = this.maybeGetCompMetas(...specs);
838
+ if (missingSpecs.length === 0) {
839
+ return prepComponentData(this.bundle, existingMetas, opts);
840
+ }
841
+ return yield returnWithSpecsToFetch(missingSpecs);
842
+ });
843
+ }
844
+ fetchComponentData(...args) {
845
+ return __async(this, null, function* () {
846
+ const { specs, opts } = parseFetchComponentDataArgs(...args);
847
+ const data = yield this.maybeFetchComponentData(specs, opts);
848
+ if (!data) {
849
+ const { missing: missingSpecs } = this.maybeGetCompMetas(...specs);
850
+ throw new Error(
851
+ `Unable to find components ${missingSpecs.map(getLookupSpecName).join(", ")}`
852
+ );
853
+ }
854
+ return data;
855
+ });
856
+ }
857
+ fetchPages(opts) {
858
+ return __async(this, null, function* () {
859
+ this.maybeReportClientSideFetch(
860
+ () => `Daouy: fetching all page metadata in the browser`
861
+ );
862
+ const data = yield this.fetchAllData();
863
+ return data.components.filter(
864
+ (comp) => comp.isPage && comp.path && ((opts == null ? void 0 : opts.includeDynamicPages) || !isDynamicPagePath(comp.path))
865
+ );
866
+ });
867
+ }
868
+ fetchComponents() {
869
+ return __async(this, null, function* () {
870
+ this.maybeReportClientSideFetch(
871
+ () => `Daouy: fetching all component metadata in the browser`
872
+ );
873
+ const data = yield this.fetchAllData();
874
+ return data.components;
875
+ });
876
+ }
877
+ getActiveSplits() {
878
+ return this.bundle.activeSplits;
879
+ }
880
+ getChunksUrl(bundle, modules) {
881
+ return this.fetcher.getChunksUrl(bundle, modules);
882
+ }
883
+ fetchMissingData(opts) {
884
+ return __async(this, null, function* () {
885
+ this.maybeReportClientSideFetch(
886
+ () => `Daouy: fetching missing components in the browser: ${opts.missingSpecs.map((spec) => getLookupSpecName(spec)).join(", ")}`
887
+ );
888
+ return this.fetchAllData();
889
+ });
890
+ }
891
+ maybeReportClientSideFetch(mkMsg) {
892
+ if (isBrowser && this.opts.onClientSideFetch) {
893
+ const msg = mkMsg();
894
+ if (this.opts.onClientSideFetch === "warn") {
895
+ console.warn(msg);
896
+ } else {
897
+ throw new Error(msg);
898
+ }
899
+ }
900
+ }
901
+ fetchAllData() {
902
+ return __async(this, null, function* () {
903
+ var _a;
904
+ const bundle = yield this.fetcher.fetchAllData();
905
+ this.mergeBundle(bundle);
906
+ (_a = this.onBundleFetched) == null ? void 0 : _a.call(this);
907
+ return bundle;
908
+ });
909
+ }
910
+ mergeBundle(newBundle) {
911
+ var _a, _b;
912
+ newBundle.bundleKey = (_a = newBundle.bundleKey) != null ? _a : null;
913
+ if (newBundle.bundleKey && this.bundle.bundleKey && newBundle.bundleKey !== this.bundle.bundleKey) {
914
+ console.warn(
915
+ `Daouy Error: Different code export hashes. This can happen if your app is using different loaders with different project IDs or project versions.
916
+ Conflicting values:
917
+ ${newBundle.bundleKey}
918
+ ${this.bundle.bundleKey}`
919
+ );
920
+ }
921
+ this.bundle = mergeBundles(newBundle, this.bundle);
922
+ (_b = this.onBundleMerged) == null ? void 0 : _b.call(this);
923
+ }
924
+ getBundle() {
925
+ return this.bundle;
926
+ }
927
+ clearCache() {
928
+ this.bundle = {
929
+ modules: {
930
+ browser: [],
931
+ server: []
932
+ },
933
+ components: [],
934
+ globalGroups: [],
935
+ projects: [],
936
+ activeSplits: [],
937
+ bundleKey: null,
938
+ deferChunksByDefault: false,
939
+ disableRootLoadingBoundaryByDefault: false,
940
+ filteredIds: {}
941
+ };
942
+ this.registry.clear();
943
+ }
944
+ registerModules(modules) {
945
+ if (Object.keys(modules).some(
946
+ (name) => this.registry.getRegisteredModule(name) !== modules[name]
947
+ )) {
948
+ if (!this.registry.isEmpty()) {
949
+ console.warn(
950
+ "Calling DaouyComponentLoader.registerModules() after Daouy component has rendered; starting over."
951
+ );
952
+ this.registry.clear();
953
+ }
954
+ for (const key of Object.keys(modules)) {
955
+ this.registry.register(key, modules[key]);
956
+ }
957
+ }
958
+ }
959
+ substituteComponent(component, name) {
960
+ this.internalSubstituteComponent(component, name, void 0);
961
+ }
962
+ internalSubstituteComponent(component, name, codeComponentHelpers) {
963
+ if (!this.isRegistryEmpty()) {
964
+ console.warn(
965
+ "Calling DaouyComponentLoader.registerSubstitution() after Daouy component has rendered; starting over."
966
+ );
967
+ this.clearRegistry();
968
+ }
969
+ this.subs.push({ lookup: name, component, codeComponentHelpers });
970
+ }
971
+ refreshRegistry() {
972
+ for (const sub of this.subs) {
973
+ const metas = getCompMetas(this.getBundle().components, sub.lookup);
974
+ metas.forEach((meta) => {
975
+ SUBSTITUTED_COMPONENTS[meta.id] = sub.component;
976
+ if (sub.codeComponentHelpers) {
977
+ REGISTERED_CODE_COMPONENT_HELPERS[meta.id] = sub.codeComponentHelpers;
978
+ }
979
+ });
980
+ }
981
+ this.registry.updateModules(this.getBundle());
982
+ }
983
+ isRegistryEmpty() {
984
+ return this.registry.isEmpty();
985
+ }
986
+ clearRegistry() {
987
+ this.registry.clear();
988
+ }
989
+ setGlobalVariants(globalVariants) {
990
+ this.globalVariants = globalVariants;
991
+ }
992
+ getGlobalVariants() {
993
+ return this.globalVariants;
994
+ }
995
+ registerPrefetchedBundle(bundle) {
996
+ if (!isBrowser) {
997
+ const cachedBundle = internal_getCachedBundleInNodeServer(this.opts);
998
+ if (cachedBundle) {
999
+ this.mergeBundle(cachedBundle);
1000
+ }
1001
+ }
1002
+ this.mergeBundle(bundle);
1003
+ }
1004
+ getLookup() {
1005
+ return new ComponentLookup(this.getBundle(), this.registry);
1006
+ }
1007
+ trackConversion(_value = 0) {
1008
+ }
1009
+ getActiveVariation(opts) {
1010
+ return __async(this, null, function* () {
1011
+ yield this.fetchComponents();
1012
+ return getActiveVariation(__spreadProps(__spreadValues({}, opts), {
1013
+ splits: this.getBundle().activeSplits
1014
+ }));
1015
+ });
1016
+ }
1017
+ getTeamIds() {
1018
+ return uniq(
1019
+ this.getBundle().projects.map(
1020
+ (p) => p.teamId ? `${p.teamId}${p.indirect ? "@indirect" : ""}` : null
1021
+ ).filter((x) => !!x)
1022
+ );
1023
+ }
1024
+ getProjectIds() {
1025
+ return uniq(
1026
+ this.getBundle().projects.map(
1027
+ (p) => `${p.id}${p.indirect ? "@indirect" : ""}`
1028
+ )
1029
+ );
1030
+ }
1031
+ trackRender(_opts) {
1032
+ }
1033
+ loadServerQueriesModule(fileName) {
1034
+ return this.registry.load(fileName);
1035
+ }
1036
+ };
1037
+ var DaouyComponentLoader = class {
1038
+ constructor(internal) {
1039
+ this.warnedRegisterComponent = false;
1040
+ this.__internal = internal;
1041
+ }
1042
+ /**
1043
+ * Sets global variants to be used for all components. Note that
1044
+ * this is not reactive, and will not re-render all components
1045
+ * already mounted; instead, it should be used to activate global
1046
+ * variants that should always be activated for the lifetime of this
1047
+ * app. If you'd like to reactively change the global variants,
1048
+ * you should specify them via <DaouyRootProvider />
1049
+ */
1050
+ setGlobalVariants(globalVariants) {
1051
+ this.__internal.setGlobalVariants(globalVariants);
1052
+ }
1053
+ registerModules(modules) {
1054
+ this.__internal.registerModules(modules);
1055
+ }
1056
+ /**
1057
+ * Register custom components that should be swapped in for
1058
+ * components defined in your project. You can use this to
1059
+ * swap in / substitute a Daouy component with a "real" component.
1060
+ */
1061
+ substituteComponent(component, name) {
1062
+ this.__internal.substituteComponent(component, name);
1063
+ }
1064
+ registerComponent(component, metaOrName) {
1065
+ if (metaOrName && typeof metaOrName === "object" && "props" in metaOrName) {
1066
+ this.__internal.registerComponent(component, metaOrName);
1067
+ } else {
1068
+ if (process.env.NODE_ENV === "development" && !this.warnedRegisterComponent) {
1069
+ console.warn(
1070
+ `DaouyLoader: Using deprecated method \`registerComponent\` for component substitution. Please consider using \`substituteComponent\` instead.`
1071
+ );
1072
+ this.warnedRegisterComponent = true;
1073
+ }
1074
+ this.substituteComponent(component, metaOrName);
1075
+ }
1076
+ }
1077
+ registerFunction(fn, meta) {
1078
+ this.__internal.registerFunction(fn, meta);
1079
+ }
1080
+ registerGlobalContext(context, meta) {
1081
+ this.__internal.registerGlobalContext(context, meta);
1082
+ }
1083
+ registerTrait(trait, meta) {
1084
+ this.__internal.registerTrait(trait, meta);
1085
+ }
1086
+ registerToken(token) {
1087
+ this.__internal.registerToken(token);
1088
+ }
1089
+ fetchComponentData(...args) {
1090
+ return this.__internal.fetchComponentData(...args);
1091
+ }
1092
+ maybeFetchComponentData(...args) {
1093
+ return __async(this, null, function* () {
1094
+ return this.__internal.maybeFetchComponentData(...args);
1095
+ });
1096
+ }
1097
+ /**
1098
+ * Returns all the page component metadata for these projects.
1099
+ */
1100
+ fetchPages(opts) {
1101
+ return __async(this, null, function* () {
1102
+ return this.__internal.fetchPages(opts);
1103
+ });
1104
+ }
1105
+ /**
1106
+ * Returns all components metadata for these projects.
1107
+ */
1108
+ fetchComponents() {
1109
+ return __async(this, null, function* () {
1110
+ return this.__internal.fetchComponents();
1111
+ });
1112
+ }
1113
+ _getActiveVariation(opts) {
1114
+ return __async(this, null, function* () {
1115
+ return this.__internal.getActiveVariation(opts);
1116
+ });
1117
+ }
1118
+ getActiveVariation(opts) {
1119
+ return __async(this, null, function* () {
1120
+ return this._getActiveVariation({
1121
+ traits: opts.traits,
1122
+ getKnownValue: (key) => {
1123
+ if (opts.known) {
1124
+ return opts.known[key];
1125
+ } else {
1126
+ const cookies = getDaouyCookieValues();
1127
+ return cookies[key];
1128
+ }
1129
+ },
1130
+ updateKnownValue: (key, value) => {
1131
+ if (!opts.known) {
1132
+ updateDaouyCookieValue(key, value);
1133
+ }
1134
+ }
1135
+ });
1136
+ });
1137
+ }
1138
+ getChunksUrl(bundle, modules) {
1139
+ return this.__internal.getChunksUrl(bundle, modules);
1140
+ }
1141
+ getExternalVariation(variation, filters) {
1142
+ return getExternalIds(this.getActiveSplits(), variation, filters);
1143
+ }
1144
+ getActiveSplits() {
1145
+ return this.__internal.getActiveSplits();
1146
+ }
1147
+ trackConversion(value = 0) {
1148
+ this.__internal.trackConversion(value);
1149
+ }
1150
+ clearCache() {
1151
+ return this.__internal.clearCache();
1152
+ }
1153
+ getExecFuncModule(renderData, fileNameKey) {
1154
+ if (renderData.entryCompMetas.length === 0) {
1155
+ return void 0;
1156
+ }
1157
+ const fileName = renderData.entryCompMetas[0][fileNameKey];
1158
+ if (!fileName) {
1159
+ return void 0;
1160
+ }
1161
+ return this.__internal.loadServerQueriesModule(fileName);
1162
+ }
1163
+ unstable__getServerQueriesData(renderData, $ctx) {
1164
+ return __async(this, null, function* () {
1165
+ const module = this.getExecFuncModule(
1166
+ renderData,
1167
+ "serverQueriesExecFuncFileName"
1168
+ );
1169
+ try {
1170
+ const $serverQueries = yield module == null ? void 0 : module.executeServerQueries($ctx);
1171
+ return $serverQueries;
1172
+ } catch (err) {
1173
+ console.error("Error executing server queries function", err);
1174
+ return {};
1175
+ }
1176
+ });
1177
+ }
1178
+ unstable__generateMetadata(renderData, props) {
1179
+ return __async(this, null, function* () {
1180
+ var _a;
1181
+ const module = this.getExecFuncModule(
1182
+ renderData,
1183
+ "generateMetadataFuncFileName"
1184
+ );
1185
+ const fallback = ((_a = renderData.entryCompMetas[0]) == null ? void 0 : _a.pageMetadata) || {};
1186
+ if (!module) {
1187
+ return fallback;
1188
+ }
1189
+ try {
1190
+ const metadata = yield module.generateMetadata(props);
1191
+ return metadata;
1192
+ } catch (err) {
1193
+ return fallback;
1194
+ }
1195
+ });
1196
+ }
1197
+ };
1198
+
1199
+ // src/loader-client.ts
1200
+ var InternalDaouyComponentLoader = class extends BaseInternalDaouyComponentLoader {
1201
+ constructor(opts) {
1202
+ super({
1203
+ opts,
1204
+ fetcher: new DaouyModulesFetcher2(opts),
1205
+ onBundleMerged: () => {
1206
+ this.refreshRegistry();
1207
+ },
1208
+ onBundleFetched: () => {
1209
+ this.roots.forEach((watcher) => {
1210
+ var _a;
1211
+ return (_a = watcher.onDataFetched) == null ? void 0 : _a.call(watcher);
1212
+ });
1213
+ },
1214
+ builtinModules: {
1215
+ react: React3,
1216
+ "react-dom": ReactDOM,
1217
+ "react/jsx-runtime": jsxRuntime,
1218
+ "react/jsx-dev-runtime": jsxDevRuntime,
1219
+ // Also inject @daouy/query and @daouy/host to use the
1220
+ // same contexts here and in loader-downloaded code.
1221
+ "@daouy/query": DaouyQuery,
1222
+ "@daouy/data-sources-context": DaouyDataSourcesContext,
1223
+ "@daouy/host": DaouyHost,
1224
+ "@daouy/loader-runtime-registry": {
1225
+ components: SUBSTITUTED_COMPONENTS,
1226
+ globalVariantHooks: SUBSTITUTED_GLOBAL_VARIANT_HOOKS,
1227
+ codeComponentHelpers: REGISTERED_CODE_COMPONENT_HELPERS,
1228
+ functions: REGISTERED_CUSTOM_FUNCTIONS
1229
+ }
1230
+ }
1231
+ });
1232
+ this.roots = [];
1233
+ }
1234
+ registerComponent(component, meta) {
1235
+ var _a, _b;
1236
+ const stateHelpers = Object.fromEntries(
1237
+ Object.entries((_a = meta.states) != null ? _a : {}).filter(
1238
+ ([_, stateSpec]) => Object.keys(stateSpec).some((key) => stateHelpersKeys.includes(key))
1239
+ ).map(([stateName, stateSpec]) => [
1240
+ stateName,
1241
+ Object.fromEntries(
1242
+ stateHelpersKeys.filter((key) => key in stateSpec).map((key) => [key, stateSpec[key]])
1243
+ )
1244
+ ])
1245
+ );
1246
+ const helpers = { states: stateHelpers };
1247
+ this.internalSubstituteComponent(
1248
+ component,
1249
+ { name: meta.name, isCode: true },
1250
+ Object.keys(stateHelpers).length > 0 ? helpers : void 0
1251
+ );
1252
+ registerComponent(component, __spreadValues(__spreadProps(__spreadValues({}, meta), {
1253
+ // Import path is not used as we will use component substitution
1254
+ importPath: (_b = meta.importPath) != null ? _b : ""
1255
+ }), Object.keys(stateHelpers).length > 0 ? {
1256
+ componentHelpers: {
1257
+ helpers,
1258
+ importPath: "",
1259
+ importName: ""
1260
+ }
1261
+ } : {}));
1262
+ }
1263
+ registerFunction(fn, meta) {
1264
+ var _a;
1265
+ registerFunction(fn, __spreadProps(__spreadValues({}, meta), {
1266
+ importPath: (_a = meta.importPath) != null ? _a : ""
1267
+ }));
1268
+ internalSetRegisteredFunction(fn, meta);
1269
+ }
1270
+ registerGlobalContext(context, meta) {
1271
+ var _a;
1272
+ this.substituteComponent(context, { name: meta.name, isCode: true });
1273
+ registerGlobalContext(context, __spreadProps(__spreadValues({}, meta), {
1274
+ importPath: (_a = meta.importPath) != null ? _a : ""
1275
+ }));
1276
+ }
1277
+ registerTrait(trait, meta) {
1278
+ registerTrait(trait, meta);
1279
+ }
1280
+ registerToken(token) {
1281
+ registerToken(token);
1282
+ }
1283
+ subscribeDaouyRoot(watcher) {
1284
+ this.roots.push(watcher);
1285
+ }
1286
+ unsubscribeDaouyRoot(watcher) {
1287
+ const index = this.roots.indexOf(watcher);
1288
+ if (index >= 0) {
1289
+ this.roots.splice(index, 1);
1290
+ }
1291
+ }
1292
+ refreshRegistry() {
1293
+ for (const globalGroup of this.getBundle().globalGroups) {
1294
+ if (globalGroup.type !== "global-screen") {
1295
+ SUBSTITUTED_GLOBAL_VARIANT_HOOKS[globalGroup.id] = createUseGlobalVariant(globalGroup.name, globalGroup.projectId);
1296
+ }
1297
+ }
1298
+ super.refreshRegistry();
1299
+ }
1300
+ };
1301
+
1302
+ // src/index.ts
1303
+ import {
1304
+ DataCtxReader,
1305
+ DataProvider,
1306
+ GlobalActionsContext,
1307
+ GlobalActionsProvider,
1308
+ PageParamsProvider as PageParamsProvider2,
1309
+ DaouyCanvasContext,
1310
+ DaouyCanvasHost,
1311
+ DaouyTranslatorContext,
1312
+ repeatedElement,
1313
+ useDataEnv,
1314
+ useDaouyCanvasComponentInfo,
1315
+ useDaouyCanvasContext,
1316
+ useSelector,
1317
+ useSelectors
1318
+ } from "@daouy/host";
1319
+ import { useDaouyQueryData } from "@daouy/query";
1320
+
1321
+ // src/PlasmicComponent.tsx
1322
+ import * as React5 from "react";
1323
+
1324
+ // src/usePlasmicComponent.tsx
1325
+ import * as React4 from "react";
1326
+ function useDaouyComponent(spec, opts = {}) {
1327
+ const rootContext = useDaouyRootContext();
1328
+ if (!rootContext) {
1329
+ throw new Error(
1330
+ `You can only use useDaouyComponent if wrapped in <DaouyRootProvider />`
1331
+ );
1332
+ }
1333
+ const loader = rootContext.loader;
1334
+ const lookup = loader.getLookup();
1335
+ const component = lookup.hasComponent(spec) ? lookup.getComponent(spec, opts) : void 0;
1336
+ const stableSpec = useStableLookupSpec(spec);
1337
+ const isMounted = useIsMounted();
1338
+ const forceUpdate = useForceUpdate();
1339
+ React4.useEffect(() => {
1340
+ if (!component) {
1341
+ (() => __async(this, null, function* () {
1342
+ yield loader.fetchComponentData(stableSpec);
1343
+ if (isMounted()) {
1344
+ forceUpdate();
1345
+ }
1346
+ }))();
1347
+ }
1348
+ }, [component, stableSpec]);
1349
+ return component;
1350
+ }
1351
+
1352
+ // src/PlasmicComponent.tsx
1353
+ var DaouyComponentContext = React5.createContext(false);
1354
+ function DaouyComponent(props) {
1355
+ const { component, projectId, componentProps, forceOriginal } = props;
1356
+ const rootContext = useDaouyRootContext();
1357
+ const isRootLoader = !React5.useContext(DaouyComponentContext);
1358
+ if (!rootContext) {
1359
+ throw new Error(
1360
+ `You must use <DaouyRootProvider/> at the root of your app`
1361
+ );
1362
+ }
1363
+ const _a = rootContext, {
1364
+ loader,
1365
+ globalContextsProps,
1366
+ variation,
1367
+ userAuthToken,
1368
+ isUserLoading,
1369
+ authRedirectUri,
1370
+ translator
1371
+ } = _a, rest = __objRest(_a, [
1372
+ "loader",
1373
+ "globalContextsProps",
1374
+ "variation",
1375
+ "userAuthToken",
1376
+ "isUserLoading",
1377
+ "authRedirectUri",
1378
+ "translator"
1379
+ ]);
1380
+ const Component = useDaouyComponent(
1381
+ { name: component, projectId, isCode: false },
1382
+ { forceOriginal }
1383
+ );
1384
+ React5.useEffect(() => {
1385
+ if (isRootLoader) {
1386
+ const meta = loader.getLookup().getComponentMeta({ name: component, projectId });
1387
+ if (meta) {
1388
+ loader.trackRender({
1389
+ renderCtx: {
1390
+ rootProjectId: meta.projectId,
1391
+ rootComponentId: meta.id,
1392
+ rootComponentName: component,
1393
+ teamIds: loader.getTeamIds(),
1394
+ projectIds: loader.getProjectIds()
1395
+ },
1396
+ variation
1397
+ });
1398
+ }
1399
+ }
1400
+ }, [component, projectId, loader, variation]);
1401
+ const element = React5.useMemo(() => {
1402
+ var _a2;
1403
+ if (!Component) {
1404
+ return null;
1405
+ }
1406
+ let elt = /* @__PURE__ */ React5.createElement(Component, __spreadValues({}, componentProps));
1407
+ if (isRootLoader) {
1408
+ const lookup = loader.getLookup();
1409
+ const ReactWebRootProvider = lookup.getRootProvider();
1410
+ const StyleTokensProvider = lookup.maybeGetStyleTokensProvider(
1411
+ {
1412
+ name: component,
1413
+ projectId
1414
+ },
1415
+ rootContext.styleTokenOverridesProjectId
1416
+ );
1417
+ const GlobalContextsProvider = lookup.getGlobalContextsProvider({
1418
+ name: component,
1419
+ projectId
1420
+ });
1421
+ elt = /* @__PURE__ */ React5.createElement(
1422
+ ReactWebRootProvider,
1423
+ __spreadProps(__spreadValues({}, rest), {
1424
+ userAuthToken,
1425
+ isUserLoading,
1426
+ authRedirectUri,
1427
+ i18n: {
1428
+ translator,
1429
+ tagPrefix: (_a2 = loader.opts.i18n) == null ? void 0 : _a2.tagPrefix
1430
+ }
1431
+ }),
1432
+ /* @__PURE__ */ React5.createElement(
1433
+ MaybeWrap,
1434
+ {
1435
+ cond: !!GlobalContextsProvider,
1436
+ wrapper: (children) => /* @__PURE__ */ React5.createElement(GlobalContextsProvider, __spreadValues({}, globalContextsProps), children)
1437
+ },
1438
+ /* @__PURE__ */ React5.createElement(
1439
+ MaybeWrap,
1440
+ {
1441
+ cond: !!StyleTokensProvider,
1442
+ wrapper: (children) => /* @__PURE__ */ React5.createElement(StyleTokensProvider, null, children)
1443
+ },
1444
+ /* @__PURE__ */ React5.createElement(DaouyComponentContext.Provider, { value: true }, elt)
1445
+ )
1446
+ )
1447
+ );
1448
+ }
1449
+ return elt;
1450
+ }, [
1451
+ Component,
1452
+ componentProps,
1453
+ loader,
1454
+ isRootLoader,
1455
+ component,
1456
+ projectId,
1457
+ globalContextsProps,
1458
+ userAuthToken,
1459
+ // Just use the token to memo, `user` should be derived from it
1460
+ isUserLoading,
1461
+ authRedirectUri
1462
+ ]);
1463
+ return element;
1464
+ }
1465
+
1466
+ // src/prepass-client.ts
1467
+ import {
1468
+ extractDaouyQueryData as internalExtractQueryData,
1469
+ daouyPrepass as internalDaouyPrepass
1470
+ } from "@daouy/prepass";
1471
+ function extractDaouyQueryData(element) {
1472
+ return internalExtractQueryData(element);
1473
+ }
1474
+ function daouyPrepass(element) {
1475
+ return internalDaouyPrepass(element);
1476
+ }
1477
+
1478
+ // src/render.tsx
1479
+ import { extractDaouyQueryData as extractDaouyQueryData2 } from "@daouy/prepass";
1480
+ import React6 from "react";
1481
+ import ReactDOM2 from "react-dom";
1482
+ import { renderToString as reactRenderToString } from "react-dom/server";
1483
+ function renderToElement(_0, _1, _2) {
1484
+ return __async(this, arguments, function* (loader, target, lookup, opts = {}) {
1485
+ return new Promise((resolve) => {
1486
+ const element = makeElement(loader, lookup, opts);
1487
+ ReactDOM2.render(element, target, () => resolve());
1488
+ });
1489
+ });
1490
+ }
1491
+ function renderToString(loader, lookup, opts = {}) {
1492
+ const element = makeElement(loader, lookup, opts);
1493
+ return reactRenderToString(element);
1494
+ }
1495
+ function extractDaouyQueryDataFromElement(_0, _1) {
1496
+ return __async(this, arguments, function* (loader, lookup, opts = {}) {
1497
+ const element = makeElement(loader, lookup, opts);
1498
+ return extractDaouyQueryData2(element);
1499
+ });
1500
+ }
1501
+ function hydrateFromElement(_0, _1, _2) {
1502
+ return __async(this, arguments, function* (loader, target, lookup, opts = {}) {
1503
+ return new Promise((resolve) => {
1504
+ const element = makeElement(loader, lookup, opts);
1505
+ ReactDOM2.hydrate(element, target, () => resolve());
1506
+ });
1507
+ });
1508
+ }
1509
+ function makeElement(loader, lookup, opts = {}) {
1510
+ return /* @__PURE__ */ React6.createElement(
1511
+ DaouyRootProvider,
1512
+ {
1513
+ loader,
1514
+ prefetchedData: opts.prefetchedData,
1515
+ globalVariants: opts.globalVariants,
1516
+ prefetchedQueryData: opts.prefetchedQueryData,
1517
+ pageParams: opts.pageParams,
1518
+ pageQuery: opts.pageQuery
1519
+ },
1520
+ /* @__PURE__ */ React6.createElement(
1521
+ DaouyComponent,
1522
+ {
1523
+ component: typeof lookup === "string" ? lookup : lookup.name,
1524
+ projectId: typeof lookup === "string" ? void 0 : lookup.projectId,
1525
+ componentProps: opts.componentProps
1526
+ }
1527
+ )
1528
+ );
1529
+ }
1530
+
1531
+ // src/index.ts
1532
+ function initDaouyLoader(opts) {
1533
+ const internal = new InternalDaouyComponentLoader(opts);
1534
+ return new DaouyComponentLoader(internal);
1535
+ }
1536
+ export {
1537
+ DaouyCanvasContext,
1538
+ DaouyCanvasHost,
1539
+ DaouyComponent,
1540
+ DaouyComponentLoader,
1541
+ DaouyRootProvider,
1542
+ DaouyTranslatorContext,
1543
+ DataCtxReader,
1544
+ DataProvider,
1545
+ GlobalActionsContext,
1546
+ GlobalActionsProvider,
1547
+ InternalDaouyComponentLoader,
1548
+ PageParamsProvider2 as PageParamsProvider,
1549
+ convertBundlesToComponentRenderData,
1550
+ daouyPrepass,
1551
+ extractDaouyQueryData,
1552
+ extractDaouyQueryDataFromElement,
1553
+ hydrateFromElement,
1554
+ initDaouyLoader,
1555
+ matchesPagePath,
1556
+ renderToElement,
1557
+ renderToString,
1558
+ repeatedElement,
1559
+ useDaouyCanvasComponentInfo,
1560
+ useDaouyCanvasContext,
1561
+ useDaouyComponent,
1562
+ useDaouyQueryData,
1563
+ useDataEnv,
1564
+ useSelector,
1565
+ useSelectors
1566
+ };
1567
+ //# sourceMappingURL=index.esm.js.map