@valbuild/shared 0.122.0 → 0.123.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,389 @@
1
+ 'use strict';
2
+
3
+ var core = require('@valbuild/core');
4
+
5
+ var VAL_CONFIG_SESSION_STORAGE_KEY = "val-config";
6
+ var VAL_THEME_SESSION_STORAGE_KEY = "val-theme";
7
+ var VAL_AI_SESSION_STORAGE_KEY = "val-ai-session";
8
+
9
+ function _typeof(o) {
10
+ "@babel/helpers - typeof";
11
+
12
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
13
+ return typeof o;
14
+ } : function (o) {
15
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
16
+ }, _typeof(o);
17
+ }
18
+
19
+ /**
20
+ * The protocol between the studio's canvas and the page inside it.
21
+ *
22
+ * The canvas shows the running site in a frame. That frame is a different
23
+ * document — the customer's app, rendered by their components — so the studio
24
+ * cannot reach into it, and it cannot reach out. Everything they say to each
25
+ * other goes through `postMessage`, and this is the vocabulary.
26
+ *
27
+ * It lives in `shared` because both halves have to agree on it: the page half
28
+ * ships in `@valbuild/next`, the studio half in `@valbuild/ui`, and a message
29
+ * shape defined twice is a message shape that will differ once.
30
+ *
31
+ * ## Why a query parameter turns it on
32
+ *
33
+ * The frame has to render the page as Val sees it — draft content, with
34
+ * `data-val-path` on every element Val tracks — while *not* showing Val's own
35
+ * overlay, because the studio is already the UI. Nothing about the cookies can
36
+ * express that: they are per-origin, and the studio and the page share an
37
+ * origin, so a cookie would change the customer's own tabs too. A parameter on
38
+ * the frame's URL is scoped to exactly the one document that needs it.
39
+ */
40
+
41
+ /** Marks a page load as the studio's canvas frame. */
42
+ var VAL_CANVAS_PARAM = "val_canvas";
43
+
44
+ /**
45
+ * Every message is tagged with this, and the tag is checked on receipt.
46
+ *
47
+ * A window receives messages from anything that has a handle on it —
48
+ * extensions, embeds, other frames — and `event.data` is whatever they chose to
49
+ * send. Checking a discriminator before reading anything else is what keeps a
50
+ * stray message from being read as a canvas instruction.
51
+ */
52
+ var VAL_CANVAS_MESSAGE = "val-canvas";
53
+
54
+ /** One element on the page that Val has a path for. */
55
+
56
+ /** What the page tells the studio. */
57
+
58
+ /** What the studio tells the page. */
59
+
60
+ /** Narrow an unknown `event.data` to a message from the page. */
61
+ function isValCanvasPageMessage(data) {
62
+ if (_typeof(data) !== "object" || data === null) return false;
63
+ var message = data;
64
+ if (message.val !== VAL_CANVAS_MESSAGE) return false;
65
+ return message.type === "ready" || message.type === "elements" || message.type === "clicked" || message.type === "pinch" || message.type === "zoom" || message.type === "refreshing";
66
+ }
67
+
68
+ /** Narrow an unknown `event.data` to a message from the studio. */
69
+ function isValCanvasStudioMessage(data) {
70
+ if (_typeof(data) !== "object" || data === null) return false;
71
+ var message = data;
72
+ if (message.val !== VAL_CANVAS_MESSAGE) return false;
73
+ return message.type === "rescan" || message.type === "highlight" || message.type === "setPicking" || message.type === "sourceUpdate" || message.type === "sourcesSynced";
74
+ }
75
+
76
+ /**
77
+ * Whether this document was loaded as the studio's canvas frame.
78
+ *
79
+ * Reads the location directly rather than taking it as an argument, because
80
+ * every caller wants the answer for the document it is running in, and passing
81
+ * it around is how one of them ends up asking about the wrong one.
82
+ */
83
+ function isValCanvasFrame(search) {
84
+ try {
85
+ return new URLSearchParams(search).get(VAL_CANVAS_PARAM) !== null;
86
+ } catch (_unused) {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ /** Add the canvas marker to a page URL. */
92
+ function withValCanvasParam(url) {
93
+ var separator = url.includes("?") ? "&" : "?";
94
+ return "".concat(url).concat(separator).concat(VAL_CANVAS_PARAM, "=1");
95
+ }
96
+
97
+ function parseRoutePattern(pattern) {
98
+ if (pattern === "" || pattern === "/") {
99
+ return [];
100
+ }
101
+ var p = pattern.startsWith("/") ? pattern.slice(1) : pattern;
102
+ return p.split("/").map(function (part) {
103
+ var isOptionalParam = part.startsWith("[[") && part.endsWith("]]");
104
+ var isNonOptionalParam = part.startsWith("[") && part.endsWith("]");
105
+ var nameStart = isOptionalParam ? 2 : isNonOptionalParam ? 1 : 0;
106
+ var nameEnd = part.indexOf("]", nameStart);
107
+ var isArrayParam = part.slice(nameStart, nameStart + 3) === "...";
108
+ var paramName = part.slice(nameStart + (isArrayParam ? 3 : 0), nameEnd);
109
+ if (isOptionalParam || isNonOptionalParam) {
110
+ if (isArrayParam) {
111
+ return {
112
+ type: "array-param",
113
+ paramName: paramName,
114
+ optional: isOptionalParam
115
+ };
116
+ } else {
117
+ return {
118
+ type: "string-param",
119
+ paramName: paramName,
120
+ optional: isOptionalParam
121
+ };
122
+ }
123
+ }
124
+ return {
125
+ type: "literal",
126
+ name: part
127
+ };
128
+ });
129
+ }
130
+
131
+ function getNextAppRouterSourceFolder(moduleFilePath) {
132
+ if (moduleFilePath.startsWith("/app")) {
133
+ return "/app";
134
+ } else if (moduleFilePath.startsWith("/src/app")) {
135
+ return "/src/app";
136
+ }
137
+ return null;
138
+ }
139
+
140
+ function _toPrimitive(t, r) {
141
+ if ("object" != typeof t || !t) return t;
142
+ var e = t[Symbol.toPrimitive];
143
+ if (void 0 !== e) {
144
+ var i = e.call(t, r || "default");
145
+ if ("object" != typeof i) return i;
146
+ throw new TypeError("@@toPrimitive must return a primitive value.");
147
+ }
148
+ return ("string" === r ? String : Number)(t);
149
+ }
150
+
151
+ function _toPropertyKey(t) {
152
+ var i = _toPrimitive(t, "string");
153
+ return "symbol" == typeof i ? i : i + "";
154
+ }
155
+
156
+ function _defineProperty(e, r, t) {
157
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
158
+ value: t,
159
+ enumerable: !0,
160
+ configurable: !0,
161
+ writable: !0
162
+ }) : e[r] = t, e;
163
+ }
164
+
165
+ function ownKeys(e, r) {
166
+ var t = Object.keys(e);
167
+ if (Object.getOwnPropertySymbols) {
168
+ var o = Object.getOwnPropertySymbols(e);
169
+ r && (o = o.filter(function (r) {
170
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
171
+ })), t.push.apply(t, o);
172
+ }
173
+ return t;
174
+ }
175
+ function _objectSpread2(e) {
176
+ for (var r = 1; r < arguments.length; r++) {
177
+ var t = null != arguments[r] ? arguments[r] : {};
178
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
179
+ _defineProperty(e, r, t[r]);
180
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
181
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
182
+ });
183
+ }
184
+ return e;
185
+ }
186
+
187
+ function _arrayLikeToArray(r, a) {
188
+ (null == a || a > r.length) && (a = r.length);
189
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
190
+ return n;
191
+ }
192
+
193
+ function _unsupportedIterableToArray(r, a) {
194
+ if (r) {
195
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
196
+ var t = {}.toString.call(r).slice(8, -1);
197
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
198
+ }
199
+ }
200
+
201
+ function _createForOfIteratorHelper(r, e) {
202
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
203
+ if (!t) {
204
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
205
+ t && (r = t);
206
+ var n = 0,
207
+ F = function () {};
208
+ return {
209
+ s: F,
210
+ n: function () {
211
+ return n >= r.length ? {
212
+ done: !0
213
+ } : {
214
+ done: !1,
215
+ value: r[n++]
216
+ };
217
+ },
218
+ e: function (r) {
219
+ throw r;
220
+ },
221
+ f: F
222
+ };
223
+ }
224
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
225
+ }
226
+ var o,
227
+ a = !0,
228
+ u = !1;
229
+ return {
230
+ s: function () {
231
+ t = t.call(r);
232
+ },
233
+ n: function () {
234
+ var r = t.next();
235
+ return a = r.done, r;
236
+ },
237
+ e: function (r) {
238
+ u = !0, o = r;
239
+ },
240
+ f: function () {
241
+ try {
242
+ a || null == t.return || t.return();
243
+ } finally {
244
+ if (u) throw o;
245
+ }
246
+ }
247
+ };
248
+ }
249
+
250
+ // Strictly speaking this should be in the next package but it's shared, because we want to use it in the ui package. We want to resolve that somehow
251
+ function getNextAppRouterSitemapTree(srcFolder, paths) {
252
+ var root = {
253
+ type: "node",
254
+ name: "/",
255
+ children: []
256
+ };
257
+ var _iterator = _createForOfIteratorHelper(paths),
258
+ _step;
259
+ try {
260
+ var _loop = function _loop() {
261
+ var path = _step.value;
262
+ var urlPath = path.urlPath,
263
+ moduleFilePathS = path.moduleFilePath;
264
+ var moduleFilePath = moduleFilePathS;
265
+ if (!urlPath.startsWith("/")) {
266
+ console.error("urlPath must start with /: ".concat(urlPath));
267
+ return 0; // continue
268
+ }
269
+ var pattern = getPatternFromModuleFilePath(moduleFilePath, srcFolder);
270
+ if (urlPath === "/") {
271
+ var fullPath = "/";
272
+ root.pattern = getPatternFromModuleFilePath(moduleFilePath, srcFolder);
273
+ root.page = {
274
+ fullPath: fullPath
275
+ };
276
+ root.sourcePath = core.Internal.joinModuleFilePathAndModulePath(moduleFilePath, "\"".concat(fullPath, "\""));
277
+ root.moduleFilePath = moduleFilePath;
278
+ return 0; // continue
279
+ }
280
+ var pathParts = urlPath.split("/").slice(1).filter(Boolean);
281
+ var currentNode = root;
282
+ pathParts.forEach(function (part, index) {
283
+ var hasChildren = index < pathParts.length - 1;
284
+ var isLast = index === pathParts.length - 1;
285
+ var fullPath = "/" + pathParts.slice(0, index + 1).join("/");
286
+ var sourcePath = core.Internal.joinModuleFilePathAndModulePath(moduleFilePath, "\"".concat(fullPath, "\""));
287
+ var node = hasChildren ? _objectSpread2(_objectSpread2({
288
+ type: "node",
289
+ name: part,
290
+ pattern: pattern,
291
+ moduleFilePath: moduleFilePath
292
+ }, isLast ? {
293
+ page: {
294
+ fullPath: fullPath
295
+ },
296
+ sourcePath: sourcePath
297
+ } : {}), {}, {
298
+ children: []
299
+ }) : {
300
+ type: "leaf",
301
+ name: part,
302
+ pattern: pattern,
303
+ fullPath: fullPath,
304
+ moduleFilePath: moduleFilePath,
305
+ sourcePath: sourcePath,
306
+ children: []
307
+ };
308
+ var existingNodeIndex = currentNode.children.findIndex(function (node) {
309
+ return node.name === part;
310
+ });
311
+ if (existingNodeIndex === -1) {
312
+ currentNode.children.push(node);
313
+ if (currentNode.type === "node") {
314
+ currentNode.isLinear = true;
315
+ if (currentNode.children.length > 1) {
316
+ delete currentNode.isLinear;
317
+ }
318
+ }
319
+ currentNode = node;
320
+ } else {
321
+ var existingNode = currentNode.children[existingNodeIndex];
322
+ if (existingNode.type === "leaf" && hasChildren) {
323
+ var _sourcePath = existingNode.sourcePath;
324
+ // convert leaf to node
325
+ currentNode.children[existingNodeIndex] = {
326
+ type: "node",
327
+ name: part,
328
+ pattern: pattern,
329
+ page: {
330
+ fullPath: fullPath
331
+ },
332
+ sourcePath: _sourcePath,
333
+ children: existingNode.children,
334
+ moduleFilePath: moduleFilePath
335
+ };
336
+ currentNode = currentNode.children[existingNodeIndex];
337
+ } else if (existingNode.type === "node" && isLast) {
338
+ // add page, source path and module file path
339
+ existingNode.page = {
340
+ fullPath: fullPath
341
+ };
342
+ existingNode.sourcePath = sourcePath;
343
+ existingNode.moduleFilePath = moduleFilePath;
344
+ existingNode.pattern = pattern;
345
+ } else {
346
+ currentNode = currentNode.children[existingNodeIndex];
347
+ }
348
+ }
349
+ });
350
+ },
351
+ _ret;
352
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
353
+ _ret = _loop();
354
+ if (_ret === 0) continue;
355
+ }
356
+ } catch (err) {
357
+ _iterator.e(err);
358
+ } finally {
359
+ _iterator.f();
360
+ }
361
+ return root;
362
+ }
363
+ function getPatternFromModuleFilePath(moduleFilePath, srcFolder) {
364
+ return moduleFilePath.replace(srcFolder, "")
365
+ // TODO: hacky!
366
+ // remove route groups
367
+ .replace(/\/\([^/]+\)/g, "") // not sure we want to do this?
368
+ .replace("/page.val.ts", "").replace("/page.val.js", "");
369
+ }
370
+
371
+ exports.VAL_AI_SESSION_STORAGE_KEY = VAL_AI_SESSION_STORAGE_KEY;
372
+ exports.VAL_CANVAS_MESSAGE = VAL_CANVAS_MESSAGE;
373
+ exports.VAL_CANVAS_PARAM = VAL_CANVAS_PARAM;
374
+ exports.VAL_CONFIG_SESSION_STORAGE_KEY = VAL_CONFIG_SESSION_STORAGE_KEY;
375
+ exports.VAL_THEME_SESSION_STORAGE_KEY = VAL_THEME_SESSION_STORAGE_KEY;
376
+ exports._arrayLikeToArray = _arrayLikeToArray;
377
+ exports._createForOfIteratorHelper = _createForOfIteratorHelper;
378
+ exports._defineProperty = _defineProperty;
379
+ exports._objectSpread2 = _objectSpread2;
380
+ exports._typeof = _typeof;
381
+ exports._unsupportedIterableToArray = _unsupportedIterableToArray;
382
+ exports.getNextAppRouterSitemapTree = getNextAppRouterSitemapTree;
383
+ exports.getNextAppRouterSourceFolder = getNextAppRouterSourceFolder;
384
+ exports.getPatternFromModuleFilePath = getPatternFromModuleFilePath;
385
+ exports.isValCanvasFrame = isValCanvasFrame;
386
+ exports.isValCanvasPageMessage = isValCanvasPageMessage;
387
+ exports.isValCanvasStudioMessage = isValCanvasStudioMessage;
388
+ exports.parseRoutePattern = parseRoutePattern;
389
+ exports.withValCanvasParam = withValCanvasParam;