@webstudio-is/sdk 0.191.0 → 0.191.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +5 -5
  2. package/lib/__generated__/normalize.css.js +0 -505
  3. package/lib/index.js +0 -1300
  4. package/lib/runtime.js +0 -101
  5. package/lib/types/__generated__/normalize.css.d.ts +0 -57
  6. package/lib/types/expression.d.ts +0 -53
  7. package/lib/types/expression.test.d.ts +0 -1
  8. package/lib/types/form-fields.d.ts +0 -8
  9. package/lib/types/index.d.ts +0 -19
  10. package/lib/types/instances-utils.d.ts +0 -5
  11. package/lib/types/instances-utils.test.d.ts +0 -1
  12. package/lib/types/jsx.d.ts +0 -151
  13. package/lib/types/jsx.test.d.ts +0 -1
  14. package/lib/types/page-meta-generator.d.ts +0 -24
  15. package/lib/types/page-meta-generator.test.d.ts +0 -1
  16. package/lib/types/page-utils.d.ts +0 -24
  17. package/lib/types/page-utils.test.d.ts +0 -1
  18. package/lib/types/resource-loader.d.ts +0 -30
  19. package/lib/types/resource-loader.test.d.ts +0 -1
  20. package/lib/types/resources-generator.d.ts +0 -22
  21. package/lib/types/resources-generator.test.d.ts +0 -1
  22. package/lib/types/runtime.d.ts +0 -3
  23. package/lib/types/schema/assets.d.ts +0 -527
  24. package/lib/types/schema/breakpoints.d.ts +0 -56
  25. package/lib/types/schema/data-sources.d.ts +0 -303
  26. package/lib/types/schema/deployment.d.ts +0 -41
  27. package/lib/types/schema/instances.d.ts +0 -417
  28. package/lib/types/schema/pages.d.ts +0 -675
  29. package/lib/types/schema/props.d.ts +0 -549
  30. package/lib/types/schema/resources.d.ts +0 -121
  31. package/lib/types/schema/style-source-selections.d.ts +0 -23
  32. package/lib/types/schema/style-sources.d.ts +0 -62
  33. package/lib/types/schema/styles.d.ts +0 -2629
  34. package/lib/types/schema/webstudio.d.ts +0 -2374
  35. package/lib/types/scope.d.ts +0 -16
  36. package/lib/types/scope.test.d.ts +0 -1
  37. package/lib/types/testing.d.ts +0 -1
  38. package/lib/types/to-string.d.ts +0 -2
  39. package/lib/types/url-pattern.d.ts +0 -2
  40. package/lib/types/url-pattern.test.d.ts +0 -1
package/lib/index.js DELETED
@@ -1,1300 +0,0 @@
1
- // src/schema/assets.ts
2
- import { z } from "zod";
3
- import { FontFormat, FontMeta } from "@webstudio-is/fonts";
4
- var AssetId = z.string();
5
- var baseAsset = {
6
- id: AssetId,
7
- projectId: z.string(),
8
- size: z.number(),
9
- name: z.string(),
10
- description: z.union([z.string(), z.null()]),
11
- createdAt: z.string()
12
- };
13
- var FontAsset = z.object({
14
- ...baseAsset,
15
- format: FontFormat,
16
- meta: FontMeta,
17
- type: z.literal("font")
18
- });
19
- var ImageMeta = z.object({
20
- width: z.number(),
21
- height: z.number()
22
- });
23
- var ImageAsset = z.object({
24
- ...baseAsset,
25
- format: z.string(),
26
- meta: ImageMeta,
27
- type: z.literal("image")
28
- });
29
- var Asset = z.union([FontAsset, ImageAsset]);
30
- var Assets = z.map(AssetId, Asset);
31
-
32
- // src/schema/pages.ts
33
- import { z as z2 } from "zod";
34
- var MIN_TITLE_LENGTH = 2;
35
- var PageId = z2.string();
36
- var FolderId = z2.string();
37
- var FolderName = z2.string().refine((value) => value.trim() !== "", "Can't be empty");
38
- var Slug = z2.string().refine(
39
- (path) => /^[-a-z0-9]*$/.test(path),
40
- "Only a-z, 0-9 and - are allowed"
41
- );
42
- var Folder = z2.object({
43
- id: FolderId,
44
- name: FolderName,
45
- slug: Slug,
46
- children: z2.array(z2.union([FolderId, PageId]))
47
- });
48
- var PageName = z2.string().refine((value) => value.trim() !== "", "Can't be empty");
49
- var PageTitle = z2.string().refine(
50
- (val) => val.length >= MIN_TITLE_LENGTH,
51
- `Minimum ${MIN_TITLE_LENGTH} characters required`
52
- );
53
- var documentTypes = ["html", "xml"];
54
- var commonPageFields = {
55
- id: PageId,
56
- name: PageName,
57
- title: PageTitle,
58
- history: z2.optional(z2.array(z2.string())),
59
- rootInstanceId: z2.string(),
60
- systemDataSourceId: z2.string(),
61
- meta: z2.object({
62
- description: z2.string().optional(),
63
- title: z2.string().optional(),
64
- excludePageFromSearch: z2.string().optional(),
65
- language: z2.string().optional(),
66
- socialImageAssetId: z2.string().optional(),
67
- socialImageUrl: z2.string().optional(),
68
- status: z2.string().optional(),
69
- redirect: z2.string().optional(),
70
- documentType: z2.optional(z2.enum(documentTypes)),
71
- custom: z2.array(
72
- z2.object({
73
- property: z2.string(),
74
- content: z2.string()
75
- })
76
- ).optional()
77
- }),
78
- marketplace: z2.optional(
79
- z2.object({
80
- include: z2.optional(z2.boolean()),
81
- category: z2.optional(z2.string()),
82
- thumbnailAssetId: z2.optional(z2.string())
83
- })
84
- )
85
- };
86
- var HomePagePath = z2.string().refine((path) => path === "", "Home page path must be empty");
87
- var HomePage = z2.object({
88
- ...commonPageFields,
89
- path: HomePagePath
90
- });
91
- var PagePath = z2.string().refine((path) => path !== "", "Can't be empty").refine((path) => path !== "/", "Can't be just a /").refine((path) => path === "" || path.startsWith("/"), "Must start with a /").refine((path) => path.endsWith("/") === false, "Can't end with a /").refine((path) => path.includes("//") === false, "Can't contain repeating /").refine(
92
- (path) => /^[-_a-z0-9*:?\\/.]*$/.test(path),
93
- "Only a-z, 0-9, -, _, /, :, ?, . and * are allowed"
94
- ).refine(
95
- // We use /s for our system stuff like /s/css or /s/uploads
96
- (path) => path !== "/s" && path.startsWith("/s/") === false,
97
- "/s prefix is reserved for the system"
98
- ).refine(
99
- // Remix serves build artefacts like JS bundles from /build
100
- // And we cannot customize it due to bug in Remix: https://github.com/remix-run/remix/issues/2933
101
- (path) => path !== "/build" && path.startsWith("/build/") === false,
102
- "/build prefix is reserved for the system"
103
- );
104
- var Page = z2.object({
105
- ...commonPageFields,
106
- path: PagePath
107
- });
108
- var ProjectMeta = z2.object({
109
- // All fields are optional to ensure consistency and allow for the addition of new fields without requiring migration
110
- siteName: z2.string().optional(),
111
- contactEmail: z2.string().optional(),
112
- faviconAssetId: z2.string().optional(),
113
- code: z2.string().optional()
114
- });
115
- var ProjectNewRedirectPath = PagePath.or(
116
- z2.string().refine((data) => {
117
- if (data === "/") {
118
- return true;
119
- }
120
- try {
121
- new URL(data);
122
- return true;
123
- } catch {
124
- return false;
125
- }
126
- }, "Must be a valid URL")
127
- );
128
- var PageRedirect = z2.object({
129
- old: PagePath,
130
- new: ProjectNewRedirectPath,
131
- status: z2.enum(["301", "302"]).optional()
132
- });
133
- var CompilerSettings = z2.object({
134
- // All fields are optional to ensure consistency and allow for the addition of new fields without requiring migration
135
- atomicStyles: z2.boolean().optional()
136
- });
137
- var Pages = z2.object({
138
- meta: ProjectMeta.optional(),
139
- compiler: CompilerSettings.optional(),
140
- redirects: z2.array(PageRedirect).optional(),
141
- homePage: HomePage,
142
- pages: z2.array(Page),
143
- folders: z2.array(Folder).refine((folders) => folders.length > 0, "Folders can't be empty")
144
- });
145
-
146
- // src/schema/instances.ts
147
- import { z as z3 } from "zod";
148
- var TextChild = z3.object({
149
- type: z3.literal("text"),
150
- value: z3.string(),
151
- placeholder: z3.boolean().optional()
152
- });
153
- var InstanceId = z3.string();
154
- var IdChild = z3.object({
155
- type: z3.literal("id"),
156
- value: InstanceId
157
- });
158
- var ExpressionChild = z3.object({
159
- type: z3.literal("expression"),
160
- value: z3.string()
161
- });
162
- var InstanceChild = z3.union([IdChild, TextChild, ExpressionChild]);
163
- var Instance = z3.object({
164
- type: z3.literal("instance"),
165
- id: InstanceId,
166
- component: z3.string(),
167
- label: z3.string().optional(),
168
- children: z3.array(InstanceChild)
169
- });
170
- var Instances = z3.map(InstanceId, Instance);
171
- var MatcherRelation = z3.union([
172
- z3.literal("ancestor"),
173
- z3.literal("parent"),
174
- z3.literal("self"),
175
- z3.literal("child"),
176
- z3.literal("descendant")
177
- ]);
178
- var MatcherOperation = z3.object({
179
- $eq: z3.string().optional(),
180
- $neq: z3.string().optional(),
181
- $in: z3.array(z3.string()).optional(),
182
- $nin: z3.array(z3.string()).optional()
183
- });
184
- var Matcher = z3.object({
185
- relation: MatcherRelation,
186
- component: MatcherOperation.optional(),
187
- tag: MatcherOperation.optional()
188
- });
189
- var Matchers = z3.union([Matcher, z3.array(Matcher)]);
190
-
191
- // src/schema/data-sources.ts
192
- import { z as z4 } from "zod";
193
- var DataSourceId = z4.string();
194
- var DataSourceVariableValue = z4.union([
195
- z4.object({
196
- type: z4.literal("number"),
197
- // initial value of variable store
198
- value: z4.number()
199
- }),
200
- z4.object({
201
- type: z4.literal("string"),
202
- value: z4.string()
203
- }),
204
- z4.object({
205
- type: z4.literal("boolean"),
206
- value: z4.boolean()
207
- }),
208
- z4.object({
209
- type: z4.literal("string[]"),
210
- value: z4.array(z4.string())
211
- }),
212
- z4.object({
213
- type: z4.literal("json"),
214
- value: z4.unknown()
215
- })
216
- ]);
217
- var DataSource = z4.union([
218
- z4.object({
219
- type: z4.literal("variable"),
220
- id: DataSourceId,
221
- scopeInstanceId: z4.optional(z4.string()),
222
- name: z4.string(),
223
- value: DataSourceVariableValue
224
- }),
225
- z4.object({
226
- type: z4.literal("parameter"),
227
- id: DataSourceId,
228
- scopeInstanceId: z4.optional(z4.string()),
229
- name: z4.string()
230
- }),
231
- z4.object({
232
- type: z4.literal("resource"),
233
- id: DataSourceId,
234
- scopeInstanceId: z4.optional(z4.string()),
235
- name: z4.string(),
236
- resourceId: z4.string()
237
- })
238
- ]);
239
- var DataSources = z4.map(DataSourceId, DataSource);
240
-
241
- // src/schema/resources.ts
242
- import { z as z5 } from "zod";
243
- var ResourceId = z5.string();
244
- var Method = z5.union([
245
- z5.literal("get"),
246
- z5.literal("post"),
247
- z5.literal("put"),
248
- z5.literal("delete")
249
- ]);
250
- var Header = z5.object({
251
- name: z5.string(),
252
- // expression
253
- value: z5.string()
254
- });
255
- var Resource = z5.object({
256
- id: ResourceId,
257
- name: z5.string(),
258
- control: z5.optional(z5.union([z5.literal("system"), z5.literal("graphql")])),
259
- method: Method,
260
- // expression
261
- url: z5.string(),
262
- headers: z5.array(Header),
263
- // expression
264
- body: z5.optional(z5.string())
265
- });
266
- var ResourceRequest = z5.object({
267
- id: ResourceId,
268
- name: z5.string(),
269
- method: Method,
270
- url: z5.string(),
271
- headers: z5.array(Header),
272
- body: z5.optional(z5.unknown())
273
- });
274
- var Resources = z5.map(ResourceId, Resource);
275
-
276
- // src/schema/props.ts
277
- import { z as z6 } from "zod";
278
- var PropId = z6.string();
279
- var baseProp = {
280
- id: PropId,
281
- instanceId: z6.string(),
282
- name: z6.string(),
283
- required: z6.optional(z6.boolean())
284
- };
285
- var Prop = z6.union([
286
- z6.object({
287
- ...baseProp,
288
- type: z6.literal("number"),
289
- value: z6.number()
290
- }),
291
- z6.object({
292
- ...baseProp,
293
- type: z6.literal("string"),
294
- value: z6.string()
295
- }),
296
- z6.object({
297
- ...baseProp,
298
- type: z6.literal("boolean"),
299
- value: z6.boolean()
300
- }),
301
- z6.object({
302
- ...baseProp,
303
- type: z6.literal("json"),
304
- value: z6.unknown()
305
- }),
306
- z6.object({
307
- ...baseProp,
308
- type: z6.literal("asset"),
309
- value: z6.string()
310
- // asset id
311
- }),
312
- z6.object({
313
- ...baseProp,
314
- type: z6.literal("page"),
315
- value: z6.union([
316
- z6.string(),
317
- // page id
318
- z6.object({
319
- pageId: z6.string(),
320
- instanceId: z6.string()
321
- })
322
- ])
323
- }),
324
- z6.object({
325
- ...baseProp,
326
- type: z6.literal("string[]"),
327
- value: z6.array(z6.string())
328
- }),
329
- z6.object({
330
- ...baseProp,
331
- type: z6.literal("parameter"),
332
- // data source id
333
- value: z6.string()
334
- }),
335
- z6.object({
336
- ...baseProp,
337
- type: z6.literal("resource"),
338
- // resource id
339
- value: z6.string()
340
- }),
341
- z6.object({
342
- ...baseProp,
343
- type: z6.literal("expression"),
344
- // expression code
345
- value: z6.string()
346
- }),
347
- z6.object({
348
- ...baseProp,
349
- type: z6.literal("action"),
350
- value: z6.array(
351
- z6.object({
352
- type: z6.literal("execute"),
353
- args: z6.array(z6.string()),
354
- code: z6.string()
355
- })
356
- )
357
- })
358
- ]);
359
- var Props = z6.map(PropId, Prop);
360
-
361
- // src/schema/breakpoints.ts
362
- import { z as z7 } from "zod";
363
- var BreakpointId = z7.string();
364
- var Breakpoint = z7.object({
365
- id: BreakpointId,
366
- label: z7.string(),
367
- minWidth: z7.number().optional(),
368
- maxWidth: z7.number().optional()
369
- }).refine(({ minWidth, maxWidth }) => {
370
- return (
371
- // Either min or max width have to be defined
372
- minWidth !== void 0 && maxWidth === void 0 || minWidth === void 0 && maxWidth !== void 0 || // This is a base breakpoint
373
- minWidth === void 0 && maxWidth === void 0
374
- );
375
- }, "Either minWidth or maxWidth should be defined");
376
- var Breakpoints = z7.map(BreakpointId, Breakpoint);
377
- var initialBreakpoints = [
378
- { id: "placeholder", label: "Base" },
379
- { id: "placeholder", label: "Tablet", maxWidth: 991 },
380
- { id: "placeholder", label: "Mobile landscape", maxWidth: 767 },
381
- { id: "placeholder", label: "Mobile portrait", maxWidth: 479 }
382
- ];
383
-
384
- // src/schema/style-sources.ts
385
- import { z as z8 } from "zod";
386
- var StyleSourceId = z8.string();
387
- var StyleSourceToken = z8.object({
388
- type: z8.literal("token"),
389
- id: StyleSourceId,
390
- name: z8.string()
391
- });
392
- var StyleSourceLocal = z8.object({
393
- type: z8.literal("local"),
394
- id: StyleSourceId
395
- });
396
- var StyleSource = z8.union([StyleSourceToken, StyleSourceLocal]);
397
- var StyleSources = z8.map(StyleSourceId, StyleSource);
398
-
399
- // src/schema/style-source-selections.ts
400
- import { z as z9 } from "zod";
401
- var InstanceId2 = z9.string();
402
- var StyleSourceId2 = z9.string();
403
- var StyleSourceSelection = z9.object({
404
- instanceId: InstanceId2,
405
- values: z9.array(StyleSourceId2)
406
- });
407
- var StyleSourceSelections = z9.map(InstanceId2, StyleSourceSelection);
408
-
409
- // src/schema/styles.ts
410
- import { z as z10 } from "zod";
411
- import { StyleValue } from "@webstudio-is/css-engine";
412
- var StyleDeclRaw = z10.object({
413
- styleSourceId: z10.string(),
414
- breakpointId: z10.string(),
415
- state: z10.optional(z10.string()),
416
- // @todo can't figure out how to make property to be enum
417
- property: z10.string(),
418
- value: StyleValue,
419
- listed: z10.boolean().optional()
420
- });
421
- var StyleDecl = StyleDeclRaw;
422
- var getStyleDeclKey = (styleDecl) => {
423
- return `${styleDecl.styleSourceId}:${styleDecl.breakpointId}:${styleDecl.property}:${styleDecl.state ?? ""}`;
424
- };
425
- var Styles = z10.map(z10.string(), StyleDecl);
426
-
427
- // src/schema/deployment.ts
428
- import { z as z11 } from "zod";
429
- var Templates = z11.enum([
430
- "vanilla",
431
- "vercel",
432
- "netlify-functions",
433
- "netlify-edge-functions",
434
- "ssg",
435
- "ssg-netlify",
436
- "ssg-vercel"
437
- ]);
438
- var Deployment = z11.union([
439
- z11.object({
440
- destination: z11.literal("static"),
441
- name: z11.string(),
442
- assetsDomain: z11.string(),
443
- // Must be validated very strictly
444
- templates: z11.array(Templates)
445
- }),
446
- z11.object({
447
- destination: z11.literal("saas").optional(),
448
- domains: z11.array(z11.string()),
449
- assetsDomain: z11.string().optional(),
450
- /**
451
- * @deprecated This field is deprecated, use `domains` instead.
452
- */
453
- projectDomain: z11.string().optional(),
454
- excludeWstdDomainFromSearch: z11.boolean().optional()
455
- })
456
- ]);
457
-
458
- // src/schema/webstudio.ts
459
- import { z as z12 } from "zod";
460
- var WebstudioFragment = z12.object({
461
- children: z12.array(InstanceChild),
462
- instances: z12.array(Instance),
463
- assets: z12.array(Asset),
464
- dataSources: z12.array(DataSource),
465
- resources: z12.array(Resource),
466
- props: z12.array(Prop),
467
- breakpoints: z12.array(Breakpoint),
468
- styleSourceSelections: z12.array(StyleSourceSelection),
469
- styleSources: z12.array(StyleSource),
470
- styles: z12.array(StyleDecl)
471
- });
472
-
473
- // src/instances-utils.ts
474
- var ROOT_INSTANCE_ID = ":root";
475
- var traverseInstances = (instances, instanceId, callback) => {
476
- const instance = instances.get(instanceId);
477
- if (instance === void 0) {
478
- return;
479
- }
480
- const skipTraversingChildren = callback(instance);
481
- if (skipTraversingChildren === false) {
482
- return;
483
- }
484
- for (const child of instance.children) {
485
- if (child.type === "id") {
486
- traverseInstances(instances, child.value, callback);
487
- }
488
- }
489
- };
490
- var findTreeInstanceIds = (instances, rootInstanceId) => {
491
- const ids = /* @__PURE__ */ new Set([rootInstanceId]);
492
- traverseInstances(instances, rootInstanceId, (instance) => {
493
- ids.add(instance.id);
494
- });
495
- return ids;
496
- };
497
- var findTreeInstanceIdsExcludingSlotDescendants = (instances, rootInstanceId) => {
498
- const ids = /* @__PURE__ */ new Set([rootInstanceId]);
499
- traverseInstances(instances, rootInstanceId, (instance) => {
500
- ids.add(instance.id);
501
- if (instance.component === "Slot") {
502
- return false;
503
- }
504
- });
505
- return ids;
506
- };
507
- var parseComponentName = (componentName) => {
508
- const parts = componentName.split(":");
509
- let namespace;
510
- let name;
511
- if (parts.length === 1) {
512
- [name] = parts;
513
- } else {
514
- [namespace, name] = parts;
515
- }
516
- return [namespace, name];
517
- };
518
-
519
- // src/expression.ts
520
- import { parseExpressionAt } from "acorn";
521
- import { simple } from "acorn-walk";
522
- var lintExpression = ({
523
- expression,
524
- availableVariables = /* @__PURE__ */ new Set(),
525
- allowAssignment = false
526
- }) => {
527
- const diagnostics = [];
528
- const addError = (message) => {
529
- return (node) => {
530
- diagnostics.push({
531
- // tune error position after wrapping expression with parentheses
532
- from: node.start - 1,
533
- to: node.end - 1,
534
- severity: "error",
535
- message
536
- });
537
- };
538
- };
539
- if (expression.trim().length === 0) {
540
- diagnostics.push({
541
- from: 0,
542
- to: 0,
543
- severity: "error",
544
- message: "Expression cannot be empty"
545
- });
546
- return diagnostics;
547
- }
548
- try {
549
- const root = parseExpressionAt(`(${expression})`, 0, {
550
- ecmaVersion: "latest",
551
- // support parsing import to forbid explicitly
552
- sourceType: "module"
553
- });
554
- simple(root, {
555
- Identifier(node) {
556
- if (availableVariables.has(node.name) === false) {
557
- addError(`"${node.name}" is not defined in the scope`)(node);
558
- }
559
- },
560
- Literal() {
561
- },
562
- ArrayExpression() {
563
- },
564
- ObjectExpression() {
565
- },
566
- UnaryExpression() {
567
- },
568
- BinaryExpression() {
569
- },
570
- LogicalExpression() {
571
- },
572
- MemberExpression() {
573
- },
574
- ConditionalExpression() {
575
- },
576
- TemplateLiteral() {
577
- },
578
- ChainExpression() {
579
- },
580
- ParenthesizedExpression() {
581
- },
582
- AssignmentExpression(node) {
583
- if (allowAssignment === false) {
584
- addError("Assignment is supported only inside actions")(node);
585
- return;
586
- }
587
- simple(node.left, {
588
- Identifier(node2) {
589
- if (availableVariables.has(node2.name) === false) {
590
- addError(`"${node2.name}" is not defined in the scope`)(node2);
591
- }
592
- }
593
- });
594
- },
595
- // parser forbids to yield inside module
596
- YieldExpression() {
597
- },
598
- ThisExpression: addError(`"this" keyword is not supported`),
599
- FunctionExpression: addError("Functions are not supported"),
600
- UpdateExpression: addError("Increment and decrement are not supported"),
601
- CallExpression: addError("Functions are not supported"),
602
- NewExpression: addError("Classes are not supported"),
603
- SequenceExpression: addError(`Only single expression is supported`),
604
- ArrowFunctionExpression: addError("Functions are not supported"),
605
- TaggedTemplateExpression: addError("Tagged template is not supported"),
606
- ClassExpression: addError("Classes are not supported"),
607
- MetaProperty: addError("Imports are not supported"),
608
- AwaitExpression: addError(`"await" keyword is not supported`),
609
- ImportExpression: addError("Imports are not supported")
610
- });
611
- } catch (error) {
612
- const castedError = error;
613
- diagnostics.push({
614
- // tune error position after wrapping expression with parentheses
615
- from: castedError.pos - 1,
616
- to: castedError.pos - 1,
617
- severity: "error",
618
- // trim auto generated error location
619
- // to not conflict with tuned position
620
- message: castedError.message.replaceAll(/\s+\(\d+:\d+\)$/g, "")
621
- });
622
- }
623
- return diagnostics;
624
- };
625
- var isLiteralNode = (node) => {
626
- if (node.type === "Literal") {
627
- return true;
628
- }
629
- if (node.type === "ArrayExpression") {
630
- return node.elements.every((node2) => {
631
- if (node2 === null || node2.type === "SpreadElement") {
632
- return false;
633
- }
634
- return isLiteralNode(node2);
635
- });
636
- }
637
- if (node.type === "ObjectExpression") {
638
- return node.properties.every((property) => {
639
- if (property.type === "SpreadElement") {
640
- return false;
641
- }
642
- const key = property.key;
643
- const isIdentifierKey = key.type === "Identifier" && property.computed === false;
644
- const isLiteralKey = key.type === "Literal";
645
- return (isLiteralKey || isIdentifierKey) && isLiteralNode(property.value);
646
- });
647
- }
648
- return false;
649
- };
650
- var isLiteralExpression = (expression) => {
651
- try {
652
- const node = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
653
- return isLiteralNode(node);
654
- } catch {
655
- return false;
656
- }
657
- };
658
- var getExpressionIdentifiers = (expression) => {
659
- const identifiers2 = /* @__PURE__ */ new Set();
660
- try {
661
- const root = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
662
- simple(root, {
663
- Identifier: (node) => identifiers2.add(node.name),
664
- AssignmentExpression(node) {
665
- simple(node.left, {
666
- Identifier: (node2) => identifiers2.add(node2.name)
667
- });
668
- }
669
- });
670
- } catch {
671
- }
672
- return identifiers2;
673
- };
674
- var transpileExpression = ({
675
- expression,
676
- executable = false,
677
- replaceVariable
678
- }) => {
679
- let root;
680
- try {
681
- root = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
682
- } catch (error) {
683
- const message = error.message;
684
- throw Error(`${message} in ${JSON.stringify(expression)}`);
685
- }
686
- const replacements = [];
687
- const replaceIdentifier = (node, assignee) => {
688
- const newName = replaceVariable?.(node.name, assignee);
689
- if (newName) {
690
- replacements.push([node.start, node.end, newName]);
691
- }
692
- };
693
- simple(root, {
694
- Identifier: (node) => replaceIdentifier(node, false),
695
- AssignmentExpression(node) {
696
- simple(node.left, {
697
- Identifier: (node2) => replaceIdentifier(node2, true)
698
- });
699
- },
700
- MemberExpression(node) {
701
- if (executable === false || node.optional) {
702
- return;
703
- }
704
- if (node.computed === false) {
705
- const dotIndex = expression.indexOf(".", node.object.end);
706
- replacements.push([dotIndex, dotIndex, "?"]);
707
- }
708
- if (node.computed === true) {
709
- const dotIndex = expression.indexOf("[", node.object.end);
710
- replacements.push([dotIndex, dotIndex, "?."]);
711
- }
712
- }
713
- });
714
- replacements.sort(([leftStart], [rightStart]) => rightStart - leftStart);
715
- for (const [start, end, fragment] of replacements) {
716
- const before = expression.slice(0, start);
717
- const after = expression.slice(end);
718
- expression = before + fragment + after;
719
- }
720
- return expression;
721
- };
722
- var parseObjectExpression = (expression) => {
723
- const map = /* @__PURE__ */ new Map();
724
- let root;
725
- try {
726
- root = parseExpressionAt(expression, 0, { ecmaVersion: "latest" });
727
- } catch (error) {
728
- return map;
729
- }
730
- if (root.type !== "ObjectExpression") {
731
- return map;
732
- }
733
- for (const property of root.properties) {
734
- if (property.type === "SpreadElement") {
735
- continue;
736
- }
737
- if (property.computed) {
738
- continue;
739
- }
740
- let key;
741
- if (property.key.type === "Identifier") {
742
- key = property.key.name;
743
- } else if (property.key.type === "Literal" && typeof property.key.value === "string") {
744
- key = property.key.value;
745
- } else {
746
- continue;
747
- }
748
- const valueExpression = expression.slice(
749
- property.value.start,
750
- property.value.end
751
- );
752
- map.set(key, valueExpression);
753
- }
754
- return map;
755
- };
756
- var generateObjectExpression = (map) => {
757
- let generated = "{\n";
758
- for (const [key, valueExpression] of map) {
759
- const keyExpression = JSON.stringify(key);
760
- generated += ` ${keyExpression}: ${valueExpression},
761
- `;
762
- }
763
- generated += `}`;
764
- return generated;
765
- };
766
- var dataSourceVariablePrefix = "$ws$dataSource$";
767
- var encodeDataSourceVariable = (id) => {
768
- const encoded = id.replaceAll("-", "__DASH__");
769
- return `${dataSourceVariablePrefix}${encoded}`;
770
- };
771
- var decodeDataSourceVariable = (name) => {
772
- if (name.startsWith(dataSourceVariablePrefix)) {
773
- const encoded = name.slice(dataSourceVariablePrefix.length);
774
- return encoded.replaceAll("__DASH__", "-");
775
- }
776
- return;
777
- };
778
- var generateExpression = ({
779
- expression,
780
- dataSources,
781
- usedDataSources,
782
- scope
783
- }) => {
784
- return transpileExpression({
785
- expression,
786
- executable: true,
787
- replaceVariable: (identifier) => {
788
- const depId = decodeDataSourceVariable(identifier);
789
- const dep = depId ? dataSources.get(depId) : void 0;
790
- if (dep) {
791
- usedDataSources?.set(dep.id, dep);
792
- return scope.getName(dep.id, dep.name);
793
- }
794
- }
795
- });
796
- };
797
- var executeExpression = (expression) => {
798
- try {
799
- const fn = new Function(`return (${expression})`);
800
- return fn();
801
- } catch {
802
- }
803
- };
804
-
805
- // src/url-pattern.ts
806
- var tokenRegex = /:(?<name>\w+)(?<modifier>[?*]?)|(?<wildcard>(?<!:\w+)\*)/;
807
- var isPathnamePattern = (pathname) => tokenRegex.test(pathname);
808
- var tokenRegexGlobal = new RegExp(tokenRegex.source, "g");
809
- var matchPathnameParams = (pathname) => {
810
- return pathname.matchAll(tokenRegexGlobal);
811
- };
812
-
813
- // src/page-utils.ts
814
- var ROOT_FOLDER_ID = "root";
815
- var isRootFolder = ({ id }) => id === ROOT_FOLDER_ID;
816
- var findPageByIdOrPath = (idOrPath, pages) => {
817
- if (idOrPath === "" || idOrPath === "/" || idOrPath === pages.homePage.id) {
818
- return pages.homePage;
819
- }
820
- return pages.pages.find(
821
- (page) => page.id === idOrPath || getPagePath(page.id, pages) === idOrPath
822
- );
823
- };
824
- var findParentFolderByChildId = (id, folders) => {
825
- for (const folder of folders) {
826
- if (folder.children.includes(id)) {
827
- return folder;
828
- }
829
- }
830
- };
831
- var getPagePath = (id, pages) => {
832
- const foldersMap = /* @__PURE__ */ new Map();
833
- const childParentMap = /* @__PURE__ */ new Map();
834
- for (const folder of pages.folders) {
835
- foldersMap.set(folder.id, folder);
836
- for (const childId of folder.children) {
837
- childParentMap.set(childId, folder.id);
838
- }
839
- }
840
- const paths = [];
841
- let currentId = id;
842
- const allPages = [pages.homePage, ...pages.pages];
843
- for (const page of allPages) {
844
- if (page.id === id) {
845
- paths.push(page.path);
846
- currentId = childParentMap.get(page.id);
847
- break;
848
- }
849
- }
850
- while (currentId) {
851
- const folder = foldersMap.get(currentId);
852
- if (folder === void 0) {
853
- break;
854
- }
855
- paths.push(folder.slug);
856
- currentId = childParentMap.get(currentId);
857
- }
858
- return paths.reverse().join("/").replace(/\/+/g, "/");
859
- };
860
- var getStaticSiteMapXml = (pages, updatedAt) => {
861
- const allPages = [pages.homePage, ...pages.pages];
862
- return allPages.filter((page) => (page.meta.documentType ?? "html") === "html").filter(
863
- (page) => executeExpression(page.meta.excludePageFromSearch) !== true
864
- ).filter((page) => false === isPathnamePattern(page.path)).map((page) => ({
865
- path: getPagePath(page.id, pages),
866
- lastModified: updatedAt.split("T")[0]
867
- }));
868
- };
869
-
870
- // src/scope.ts
871
- import reservedIdentifiers from "reserved-identifiers";
872
- var identifiers = reservedIdentifiers({ includeGlobalProperties: true });
873
- var isReserved = (identifier) => identifiers.has(identifier);
874
- var normalizeJsName = (name) => {
875
- name = name.replaceAll(/[^\w$]/g, "");
876
- if (name.length === 0) {
877
- return "_";
878
- }
879
- if (/[A-Za-z_$]/.test(name[0]) === false) {
880
- name = `_${name}`;
881
- }
882
- if (isReserved(name)) {
883
- return `${name}_`;
884
- }
885
- return name;
886
- };
887
- var createScope = (occupiedIdentifiers = [], normalizeName = normalizeJsName, separator = "_") => {
888
- const nameById = /* @__PURE__ */ new Map();
889
- const usedNames = /* @__PURE__ */ new Set();
890
- for (const identifier of occupiedIdentifiers) {
891
- usedNames.add(identifier);
892
- }
893
- const getName = (id, preferredName) => {
894
- const cachedName = nameById.get(id);
895
- if (cachedName !== void 0) {
896
- return cachedName;
897
- }
898
- preferredName = normalizeName(preferredName);
899
- let index = 0;
900
- let scopedName = preferredName;
901
- while (usedNames.has(scopedName)) {
902
- index += 1;
903
- scopedName = `${preferredName}${separator}${index}`;
904
- }
905
- nameById.set(id, scopedName);
906
- usedNames.add(scopedName);
907
- return scopedName;
908
- };
909
- return {
910
- getName
911
- };
912
- };
913
-
914
- // src/resources-generator.ts
915
- var generateResources = ({
916
- scope,
917
- page,
918
- dataSources,
919
- props,
920
- resources
921
- }) => {
922
- const usedDataSources = /* @__PURE__ */ new Map();
923
- let generatedRequests = "";
924
- for (const resource of resources.values()) {
925
- let generatedRequest = "";
926
- const resourceName = scope.getName(resource.id, resource.name);
927
- generatedRequest += ` const ${resourceName}: ResourceRequest = {
928
- `;
929
- generatedRequest += ` id: "${resource.id}",
930
- `;
931
- generatedRequest += ` name: ${JSON.stringify(resource.name)},
932
- `;
933
- const url = generateExpression({
934
- expression: resource.url,
935
- dataSources,
936
- usedDataSources,
937
- scope
938
- });
939
- generatedRequest += ` url: ${url},
940
- `;
941
- generatedRequest += ` method: "${resource.method}",
942
- `;
943
- generatedRequest += ` headers: [
944
- `;
945
- for (const header of resource.headers) {
946
- const value = generateExpression({
947
- expression: header.value,
948
- dataSources,
949
- usedDataSources,
950
- scope
951
- });
952
- generatedRequest += ` { name: "${header.name}", value: ${value} },
953
- `;
954
- }
955
- generatedRequest += ` ],
956
- `;
957
- if (resource.body !== void 0 && resource.body.length > 0) {
958
- const body = generateExpression({
959
- expression: resource.body,
960
- dataSources,
961
- usedDataSources,
962
- scope
963
- });
964
- generatedRequest += ` body: ${body},
965
- `;
966
- }
967
- generatedRequest += ` }
968
- `;
969
- generatedRequests += generatedRequest;
970
- }
971
- let generatedVariables = "";
972
- for (const dataSource of usedDataSources.values()) {
973
- if (dataSource.type === "variable") {
974
- const name = scope.getName(dataSource.id, dataSource.name);
975
- const value = JSON.stringify(dataSource.value.value);
976
- generatedVariables += ` let ${name} = ${value}
977
- `;
978
- }
979
- if (dataSource.type === "parameter") {
980
- if (dataSource.id !== page.systemDataSourceId) {
981
- continue;
982
- }
983
- const name = scope.getName(dataSource.id, dataSource.name);
984
- generatedVariables += ` const ${name} = _props.system
985
- `;
986
- }
987
- }
988
- let generated = "";
989
- generated += `import type { System, ResourceRequest } from "@webstudio-is/sdk";
990
- `;
991
- generated += `export const getResources = (_props: { system: System }) => {
992
- `;
993
- generated += generatedVariables;
994
- generated += generatedRequests;
995
- generated += ` const _data = new Map<string, ResourceRequest>([
996
- `;
997
- for (const dataSource of dataSources.values()) {
998
- if (dataSource.type === "resource") {
999
- const name = scope.getName(dataSource.resourceId, dataSource.name);
1000
- generated += ` ["${name}", ${name}],
1001
- `;
1002
- }
1003
- }
1004
- generated += ` ])
1005
- `;
1006
- generated += ` const _action = new Map<string, ResourceRequest>([
1007
- `;
1008
- for (const prop of props.values()) {
1009
- if (prop.type === "resource") {
1010
- const name = scope.getName(prop.value, prop.name);
1011
- generated += ` ["${name}", ${name}],
1012
- `;
1013
- }
1014
- }
1015
- generated += ` ])
1016
- `;
1017
- generated += ` return { data: _data, action: _action }
1018
- `;
1019
- generated += `}
1020
- `;
1021
- return generated;
1022
- };
1023
- var getMethod = (value) => {
1024
- switch (value?.toLowerCase()) {
1025
- case "get":
1026
- return "get";
1027
- case "delete":
1028
- return "delete";
1029
- case "put":
1030
- return "put";
1031
- default:
1032
- return "post";
1033
- }
1034
- };
1035
- var replaceFormActionsWithResources = ({
1036
- props,
1037
- instances,
1038
- resources
1039
- }) => {
1040
- const formProps = /* @__PURE__ */ new Map();
1041
- for (const prop of props.values()) {
1042
- if (prop.name === "method" && prop.type === "string" && instances.get(prop.instanceId)?.component === "Form") {
1043
- let data = formProps.get(prop.instanceId);
1044
- if (data === void 0) {
1045
- data = {};
1046
- formProps.set(prop.instanceId, data);
1047
- }
1048
- data.method = prop.value;
1049
- props.delete(prop.id);
1050
- }
1051
- if (prop.name === "action" && prop.type === "string" && prop.value && instances.get(prop.instanceId)?.component === "Form") {
1052
- let data = formProps.get(prop.instanceId);
1053
- if (data === void 0) {
1054
- data = {};
1055
- formProps.set(prop.instanceId, data);
1056
- }
1057
- data.action = prop.value;
1058
- props.set(prop.id, {
1059
- id: prop.id,
1060
- instanceId: prop.instanceId,
1061
- name: prop.name,
1062
- type: "resource",
1063
- value: prop.instanceId
1064
- });
1065
- }
1066
- }
1067
- for (const [instanceId, { action, method }] of formProps) {
1068
- if (action) {
1069
- resources.set(instanceId, {
1070
- id: instanceId,
1071
- name: "action",
1072
- method: getMethod(method),
1073
- url: JSON.stringify(action),
1074
- headers: []
1075
- });
1076
- }
1077
- }
1078
- };
1079
-
1080
- // src/page-meta-generator.ts
1081
- var generatePageMeta = ({
1082
- globalScope,
1083
- page,
1084
- dataSources,
1085
- assets
1086
- }) => {
1087
- const localScope = createScope(["system", "resources"]);
1088
- const usedDataSources = /* @__PURE__ */ new Map();
1089
- const titleExpression = generateExpression({
1090
- expression: page.title,
1091
- dataSources,
1092
- usedDataSources,
1093
- scope: localScope
1094
- });
1095
- const descriptionExpression = generateExpression({
1096
- expression: page.meta.description ?? "undefined",
1097
- dataSources,
1098
- usedDataSources,
1099
- scope: localScope
1100
- });
1101
- const excludePageFromSearchExpression = generateExpression({
1102
- expression: page.meta.excludePageFromSearch ?? "undefined",
1103
- dataSources,
1104
- usedDataSources,
1105
- scope: localScope
1106
- });
1107
- const languageExpression = generateExpression({
1108
- expression: page.meta.language ?? "undefined",
1109
- dataSources,
1110
- usedDataSources,
1111
- scope: localScope
1112
- });
1113
- const socialImageAssetNameExpression = JSON.stringify(
1114
- page.meta.socialImageAssetId ? assets.get(page.meta.socialImageAssetId)?.name : void 0
1115
- );
1116
- const socialImageUrlExpression = generateExpression({
1117
- expression: page.meta.socialImageUrl ?? "undefined",
1118
- dataSources,
1119
- usedDataSources,
1120
- scope: localScope
1121
- });
1122
- const statusExpression = generateExpression({
1123
- expression: page.meta.status ?? "undefined",
1124
- dataSources,
1125
- usedDataSources,
1126
- scope: localScope
1127
- });
1128
- const redirectExpression = generateExpression({
1129
- expression: page.meta.redirect ?? "undefined",
1130
- dataSources,
1131
- usedDataSources,
1132
- scope: localScope
1133
- });
1134
- let customExpression = "";
1135
- customExpression += `[
1136
- `;
1137
- for (const customMeta of page.meta.custom ?? []) {
1138
- if (customMeta.property.trim().length === 0) {
1139
- continue;
1140
- }
1141
- const propertyExpression = JSON.stringify(customMeta.property);
1142
- const contentExpression = generateExpression({
1143
- expression: customMeta.content,
1144
- dataSources,
1145
- usedDataSources,
1146
- scope: localScope
1147
- });
1148
- customExpression += ` {
1149
- `;
1150
- customExpression += ` property: ${propertyExpression},
1151
- `;
1152
- customExpression += ` content: ${contentExpression},
1153
- `;
1154
- customExpression += ` },
1155
- `;
1156
- }
1157
- customExpression += ` ]`;
1158
- let generated = "";
1159
- generated += `export const getPageMeta = ({
1160
- `;
1161
- generated += ` system,
1162
- `;
1163
- generated += ` resources,
1164
- `;
1165
- generated += `}: {
1166
- `;
1167
- generated += ` system: System;
1168
- `;
1169
- generated += ` resources: Record<string, any>;
1170
- `;
1171
- generated += `}): PageMeta => {
1172
- `;
1173
- for (const dataSource of usedDataSources.values()) {
1174
- if (dataSource.type === "variable") {
1175
- const valueName = localScope.getName(dataSource.id, dataSource.name);
1176
- const initialValueString = JSON.stringify(dataSource.value.value);
1177
- generated += ` let ${valueName} = ${initialValueString}
1178
- `;
1179
- continue;
1180
- }
1181
- if (dataSource.type === "parameter") {
1182
- if (dataSource.id === page.systemDataSourceId) {
1183
- const valueName = localScope.getName(dataSource.id, dataSource.name);
1184
- generated += ` let ${valueName} = system
1185
- `;
1186
- }
1187
- continue;
1188
- }
1189
- if (dataSource.type === "resource") {
1190
- const valueName = localScope.getName(dataSource.id, dataSource.name);
1191
- const resourceName = globalScope.getName(
1192
- dataSource.resourceId,
1193
- dataSource.name
1194
- );
1195
- generated += ` let ${valueName} = resources.${resourceName}
1196
- `;
1197
- continue;
1198
- }
1199
- }
1200
- generated += ` return {
1201
- `;
1202
- generated += ` title: ${titleExpression},
1203
- `;
1204
- generated += ` description: ${descriptionExpression},
1205
- `;
1206
- generated += ` excludePageFromSearch: ${excludePageFromSearchExpression},
1207
- `;
1208
- generated += ` language: ${languageExpression},
1209
- `;
1210
- generated += ` socialImageAssetName: ${socialImageAssetNameExpression},
1211
- `;
1212
- generated += ` socialImageUrl: ${socialImageUrlExpression},
1213
- `;
1214
- generated += ` status: ${statusExpression},
1215
- `;
1216
- generated += ` redirect: ${redirectExpression},
1217
- `;
1218
- generated += ` custom: ${customExpression},
1219
- `;
1220
- generated += ` };
1221
- `;
1222
- generated += `};
1223
- `;
1224
- return generated;
1225
- };
1226
- export {
1227
- Asset,
1228
- Assets,
1229
- Breakpoint,
1230
- Breakpoints,
1231
- CompilerSettings,
1232
- DataSource,
1233
- DataSourceVariableValue,
1234
- DataSources,
1235
- Deployment,
1236
- ExpressionChild,
1237
- Folder,
1238
- FolderName,
1239
- FontAsset,
1240
- HomePagePath,
1241
- IdChild,
1242
- ImageAsset,
1243
- ImageMeta,
1244
- Instance,
1245
- InstanceChild,
1246
- Instances,
1247
- Matcher,
1248
- MatcherOperation,
1249
- MatcherRelation,
1250
- Matchers,
1251
- PageName,
1252
- PagePath,
1253
- PageRedirect,
1254
- PageTitle,
1255
- Pages,
1256
- ProjectNewRedirectPath,
1257
- Prop,
1258
- Props,
1259
- ROOT_FOLDER_ID,
1260
- ROOT_INSTANCE_ID,
1261
- Resource,
1262
- ResourceRequest,
1263
- Resources,
1264
- StyleDecl,
1265
- StyleSource,
1266
- StyleSourceSelection,
1267
- StyleSourceSelections,
1268
- StyleSources,
1269
- Styles,
1270
- Templates,
1271
- TextChild,
1272
- WebstudioFragment,
1273
- createScope,
1274
- decodeDataSourceVariable,
1275
- documentTypes,
1276
- encodeDataSourceVariable,
1277
- executeExpression,
1278
- findPageByIdOrPath,
1279
- findParentFolderByChildId,
1280
- findTreeInstanceIds,
1281
- findTreeInstanceIdsExcludingSlotDescendants,
1282
- generateExpression,
1283
- generateObjectExpression,
1284
- generatePageMeta,
1285
- generateResources,
1286
- getExpressionIdentifiers,
1287
- getPagePath,
1288
- getStaticSiteMapXml,
1289
- getStyleDeclKey,
1290
- initialBreakpoints,
1291
- isLiteralExpression,
1292
- isPathnamePattern,
1293
- isRootFolder,
1294
- lintExpression,
1295
- matchPathnameParams,
1296
- parseComponentName,
1297
- parseObjectExpression,
1298
- replaceFormActionsWithResources,
1299
- transpileExpression
1300
- };