@superwall/cli 2.4.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{apple-Bx_fm5M-.js → apple-Dyr7OFBx.js} +16 -15
- package/dist/approve-Czs1-JO9.js +186 -0
- package/dist/{assets-W5yvyf0V.js → assets-BrB9jQPQ.js} +3 -3
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +3 -3
- package/dist/{billing-C4lXR0xG.js → billing-D5qqIlVb.js} +3 -3
- package/dist/{bind-82oTpHZ3.js → bind-B3eEcRyp.js} +4 -4
- package/dist/browser-Bp3yRKlU.js +36 -0
- package/dist/{build-7_8cBgBm.js → build-DD9pSwHX.js} +9 -7
- package/dist/{client-ltxxHuxn.js → client-AI9H4GGB.js} +3 -3
- package/dist/{create-Dk8U_B49.js → create-B4m-IKlr.js} +8 -8
- package/dist/create-CJljlkJK.js +20 -0
- package/dist/{create-DEyveHS6.js → create-ChfgWpiM.js} +39 -67
- package/dist/{doctor-Df2GwS4K.js → doctor-XtXW6tKE.js} +6 -6
- package/dist/download-2Zu2I_Og.js +58 -0
- package/dist/{drivers-CTyYdBL7.js → drivers-CMEL13gp.js} +3 -3
- package/dist/entry.js +25 -24
- package/dist/{environment-djS0ik60.js → environment-BWT2S4qC.js} +3 -2
- package/dist/{existing-Das3PHGG.js → existing-b0GxFcnc.js} +2 -2
- package/dist/{session-CV0P8BjK.js → git-D7AVdugb.js} +96 -334
- package/dist/held-CX7Zf8u-.js +17 -0
- package/dist/{held-B8EFWDEc.js → held-D3PUNky2.js} +7 -7
- package/dist/install-CVUXsx8c.js +103 -0
- package/dist/{integrate-Cz48dm_h.js → integrate-qvKd9pVW.js} +27 -25
- package/dist/{login-girc324T.js → login-COmGHrU5.js} +2 -1
- package/dist/login-ClnJi1Ea.js +17 -0
- package/dist/{login-CiK5T4w8.js → login-PMoXUGqq.js} +8 -41
- package/dist/{lookup-us5vu5od.js → lookup-gjcKIZvh.js} +3 -2
- package/dist/{migrate-DaVwhdov.js → migrate-SkkLLdmr.js} +30 -25
- package/dist/{migration-cS6UGeUj.js → migration-DS44-3Zr.js} +9 -9
- package/dist/{notification-url-Hg42tAbW.js → notification-url-BjQPLf4-.js} +4 -4
- package/dist/{open-BIuOZ9ka.js → open-DQpm2yVs.js} +2 -2
- package/dist/{org-BrR4HGvl.js → org-C04eAO-j.js} +3 -2
- package/dist/organization-BOECL3vZ.js +39 -0
- package/dist/orgs-D6Kk96mG.js +81 -0
- package/dist/{paths-CdwjySxK.js → paths-REb-GrbX.js} +1 -1
- package/dist/{playbook-BJ3opYIS.js → playbook-Du4Oydbf.js} +10 -10
- package/dist/{products-DH_fK9tY.js → products-Cqq59DBQ.js} +1 -1
- package/dist/project-CP6hiHra.js +47 -0
- package/dist/{promote-BQO-1ScY.js → promote-Dm2_b1WK.js} +23 -18
- package/dist/pull-DsdOoG-D.js +36 -0
- package/dist/{pull-BhRswq6x.js → pull-F6pvO4To.js} +9 -28
- package/dist/pull-zYAbqo9n.js +106 -0
- package/dist/{push-CR110qRh.js → push-BIFLhAiO.js} +8 -6
- package/dist/push-CJVfvFZq.js +29 -0
- package/dist/push-D_l9KJZN.js +290 -0
- package/dist/push-SVzv7fzE.js +22 -0
- package/dist/{registry-DZsWoWqH.js → registry-DIJB0mJa.js} +687 -64
- package/dist/resolve--GsHj0Q1.js +171 -0
- package/dist/{resources-BMspgZO1.js → resources-BaP3p_LY.js} +3 -80
- package/dist/{run-D4V6mq8_.js → run-C5OPwhvS.js} +2 -2
- package/dist/run-CgLmD2vR.js +1345 -0
- package/dist/{scan-CRexsHOE.js → scan-Bj5y0zTZ.js} +1 -1
- package/dist/scan-v_WTE722.js +4 -0
- package/dist/{scope-Ct0_HoNq.js → scope-Bp_zwJOo.js} +5 -4
- package/dist/scope-CCb_7UvN.js +89 -0
- package/dist/sdk-TvT0p_nO.js +71 -0
- package/dist/selection-BltBpyp5.js +179 -0
- package/dist/series-TAixFBWW.js +685 -0
- package/dist/{server-Dv1VwbNh.js → server-CdVIboQn.js} +10 -8
- package/dist/server-CvJVusw3.js +29 -0
- package/dist/session-B8JNXkwN.js +6 -0
- package/dist/session-D3fgXQBt.js +219 -0
- package/dist/{session-UiPlLFn6.js → session-Ywim-P8M.js} +1 -1
- package/dist/{setup-UWLhQG3M.js → setup-zzjtTy8k.js} +9 -8
- package/dist/skills/index.json +5 -0
- package/dist/skills/superwall/SKILL.md +48 -30
- package/dist/skills/superwall/references/api.md +3 -2
- package/dist/skills/superwall-editor/SKILL.md +7 -5
- package/dist/skills/superwall-framework/SKILL.md +7 -5
- package/dist/skills/superwall-workspaces/SKILL.md +313 -0
- package/dist/skills/superwall-workspaces/references/cli.md +174 -0
- package/dist/skills/superwall-workspaces/references/slots.md +103 -0
- package/dist/{skills-CiWxt6vS.js → skills-2qYaUXGE.js} +4 -4
- package/dist/{skills-DzOvse9L.js → skills-8um2fBPS.js} +8 -8
- package/dist/{source-push-CX_k_yZD.js → source-push-kAep4gPe.js} +6 -5
- package/dist/{spinner-1uuKKZMc.js → spinner-BANVLncC.js} +16 -4
- package/dist/starter-CiLrp1cN.js +190 -0
- package/dist/status-CoYMK7QL.js +139 -0
- package/dist/{storage-CrXGgIbS.js → storage-DzP22xKn.js} +1 -1
- package/dist/storekit-D5eopLM0.js +17 -0
- package/dist/{storekit-CptdG4RJ.js → storekit-n1x0bWkQ.js} +4 -4
- package/dist/{telemetry-BqaPbM0k.js → telemetry-CXN6f-ZX.js} +1 -1
- package/dist/{token-zjjlkNDF.js → token-FmeHywYt.js} +1 -1
- package/dist/tools-skills/superwall/SKILL.md +49 -31
- package/dist/tools-skills/superwall/references/api.md +3 -2
- package/dist/tools-skills/superwall-editor/SKILL.md +7 -5
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +452 -27
- package/dist/try-BWbzgelb.js +120 -0
- package/dist/{selection-CgZJJ3FD.js → types-JdxmnCko.js} +1 -178
- package/dist/{upgrade-BBnmcyY2.js → upgrade-Bk5boOgW.js} +2 -2
- package/dist/{upgrade-AdyF7wXk.js → upgrade-CoWCEnoi.js} +2 -2
- package/package.json +5 -3
- package/dist/create-CBCDWuyo.js +0 -19
- package/dist/held-BL4oizD6.js +0 -16
- package/dist/login-DdrOmi6m.js +0 -16
- package/dist/push-B3Onn_mL.js +0 -24
- package/dist/scan-DUQjxOZf.js +0 -4
- package/dist/server-Cv-Ug9JF.js +0 -24
- package/dist/session-BCQuMcQ0.js +0 -6
- package/dist/storekit-B675ZNiA.js +0 -16
- /package/dist/{client-BZ1UbpXz.js → client-BJQXl62Q.js} +0 -0
- /package/dist/{devtools-pBl_vt03.js → devtools-ByZ6XYnn.js} +0 -0
- /package/dist/{input-vi0bou04.js → input-MDd67UIp.js} +0 -0
- /package/dist/{reports-CwwKLUh0.js → reports-CuhB1_ub.js} +0 -0
- /package/dist/{screenshot-file-tVBfUEIi.js → screenshot-file-XAS0Xy0e.js} +0 -0
- /package/dist/{storage-gRyQetN9.d.ts → storage-BjQCiTuz.d.ts} +0 -0
- /package/dist/{timing-BVxPrYq3.js → timing-Ca0TXY-A.js} +0 -0
|
@@ -0,0 +1,1345 @@
|
|
|
1
|
+
import "./token-FmeHywYt.js";
|
|
2
|
+
import "./output-Ggzq5_-t.js";
|
|
3
|
+
import "./environment-BWT2S4qC.js";
|
|
4
|
+
import "./storage-DzP22xKn.js";
|
|
5
|
+
import { t as ApiError } from "./client-AI9H4GGB.js";
|
|
6
|
+
import "./config-CGcG7GOt.js";
|
|
7
|
+
import "./spinner-BANVLncC.js";
|
|
8
|
+
import "./ui-D_qf3Gvw.js";
|
|
9
|
+
import "./orgs-D6Kk96mG.js";
|
|
10
|
+
import "./resources-BaP3p_LY.js";
|
|
11
|
+
import "./lookup-gjcKIZvh.js";
|
|
12
|
+
import "./types-JdxmnCko.js";
|
|
13
|
+
import { i as WORKSPACE_FILE } from "./scope-CCb_7UvN.js";
|
|
14
|
+
import "./download-2Zu2I_Og.js";
|
|
15
|
+
import { a as findEntrypoint, o as readManifest, r as WorkspaceError, s as readProject } from "./project-CP6hiHra.js";
|
|
16
|
+
import { C as WORKSPACE_HEADER_PREFIX, S as WORKSPACE_COMPATIBILITY_DATE, _ as METRIC_LIMITS, b as READOUT_LIMITS, c as defaultRange, d as resolveWranglerPackage, f as API_HOST, g as ENTRYPOINT_HEADER, i as seriesProblem, l as parseContextJson, m as CONTEXT_HEADER, o as SLOTS, p as BRIDGE_PROTOCOL, r as readoutProblem, s as buildContext, t as checkMetricQuery, u as bundleWorkspace, v as MOUNT_LOAD_TIMEOUT_MS, w as isInternalPath, x as TRIGGER_HEADER, y as PLATFORM_HOST } from "./series-TAixFBWW.js";
|
|
17
|
+
import { n as resolveOrganization, t as resolveAppScope } from "./organization-BOECL3vZ.js";
|
|
18
|
+
import { i as warnIfSdkBehind } from "./sdk-TvT0p_nO.js";
|
|
19
|
+
import { createRequire } from "node:module";
|
|
20
|
+
import * as fs from "node:fs";
|
|
21
|
+
import * as path from "node:path";
|
|
22
|
+
import { pathToFileURL } from "node:url";
|
|
23
|
+
import { randomBytes } from "node:crypto";
|
|
24
|
+
import * as http from "node:http";
|
|
25
|
+
|
|
26
|
+
//#region src/core/workspaces/dev/credential.ts
|
|
27
|
+
const MAX_TOKEN_RENEWALS = 3;
|
|
28
|
+
function createAgentCredential(mint) {
|
|
29
|
+
let latest;
|
|
30
|
+
let first;
|
|
31
|
+
let renewing;
|
|
32
|
+
let renewals = 0;
|
|
33
|
+
const start = () => mint().then((token) => {
|
|
34
|
+
latest = token;
|
|
35
|
+
return token;
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
current() {
|
|
39
|
+
if (latest !== void 0) return Promise.resolve(latest);
|
|
40
|
+
first ??= start().finally(() => {
|
|
41
|
+
first = void 0;
|
|
42
|
+
});
|
|
43
|
+
return first;
|
|
44
|
+
},
|
|
45
|
+
renew(rejected, { expired = false } = {}) {
|
|
46
|
+
if (renewing) return renewing;
|
|
47
|
+
if (latest !== void 0 && latest !== rejected) return Promise.resolve(latest);
|
|
48
|
+
if (!expired && renewals >= MAX_TOKEN_RENEWALS) return Promise.reject(new WorkspaceError(`The API kept refusing dev's token after ${MAX_TOKEN_RENEWALS} new ones, so it stopped making more. Check \`superwall whoami\`, then restart dev.`));
|
|
49
|
+
if (!expired) renewals += 1;
|
|
50
|
+
renewing = start().finally(() => {
|
|
51
|
+
renewing = void 0;
|
|
52
|
+
});
|
|
53
|
+
return renewing;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/core/workspaces/routes.ts
|
|
60
|
+
const WORKSPACE_ROUTE_REFUSAL = "Workspaces may not call this endpoint.";
|
|
61
|
+
const READ = new Set(["GET", "HEAD"]);
|
|
62
|
+
const WRITE = new Set([
|
|
63
|
+
"POST",
|
|
64
|
+
"PUT",
|
|
65
|
+
"PATCH",
|
|
66
|
+
"DELETE"
|
|
67
|
+
]);
|
|
68
|
+
const POST = new Set(["POST"]);
|
|
69
|
+
const ID = "[^/]+";
|
|
70
|
+
const under = (prefix) => /* @__PURE__ */ new RegExp(`^${prefix}(?:/.*)?$`);
|
|
71
|
+
const READ_WRITE_FAMILIES = [
|
|
72
|
+
"/v2/paywalls",
|
|
73
|
+
"/v2/campaigns",
|
|
74
|
+
"/v2/products",
|
|
75
|
+
"/v2/entitlements",
|
|
76
|
+
"/v2/grants",
|
|
77
|
+
"/v2/assets",
|
|
78
|
+
"/v2/surveys",
|
|
79
|
+
"/v2/retention-campaigns",
|
|
80
|
+
"/v2/retention-configurations",
|
|
81
|
+
"/v2/retention-default-messages",
|
|
82
|
+
"/v2/retention-messages"
|
|
83
|
+
];
|
|
84
|
+
const READ_FAMILIES$1 = [
|
|
85
|
+
"/v2/projects",
|
|
86
|
+
"/v2/applications",
|
|
87
|
+
"/v2/charts",
|
|
88
|
+
"/v2/users",
|
|
89
|
+
"/v3/users",
|
|
90
|
+
"/v2/onboarding",
|
|
91
|
+
"/v2/retention-onboarding",
|
|
92
|
+
"/v2/demand-score"
|
|
93
|
+
];
|
|
94
|
+
const ALLOWED = [
|
|
95
|
+
...READ_WRITE_FAMILIES.map((prefix) => ({
|
|
96
|
+
methods: READ,
|
|
97
|
+
path: under(prefix)
|
|
98
|
+
})),
|
|
99
|
+
...READ_WRITE_FAMILIES.map((prefix) => ({
|
|
100
|
+
methods: WRITE,
|
|
101
|
+
path: under(prefix)
|
|
102
|
+
})),
|
|
103
|
+
...READ_FAMILIES$1.map((prefix) => ({
|
|
104
|
+
methods: READ,
|
|
105
|
+
path: under(prefix)
|
|
106
|
+
})),
|
|
107
|
+
{
|
|
108
|
+
methods: POST,
|
|
109
|
+
path: /^\/v2\/charts\/(?:data|filter-values|acquisition-cohort-report)$/
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
methods: POST,
|
|
113
|
+
path: /^\/v2\/users\/query$/
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
methods: POST,
|
|
117
|
+
path: /^\/v2\/demand-score\/query$/
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
methods: new Set([
|
|
121
|
+
"GET",
|
|
122
|
+
"HEAD",
|
|
123
|
+
"POST"
|
|
124
|
+
]),
|
|
125
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/organizations/${ID}/query$`)
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
methods: WRITE,
|
|
129
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/projects/${ID}/custom-stores(?:/${ID})?$`)
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
methods: POST,
|
|
133
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/custom-stores/${ID}/events$`)
|
|
134
|
+
}
|
|
135
|
+
];
|
|
136
|
+
const DENIED = [
|
|
137
|
+
/* @__PURE__ */ new RegExp(`^/v2/paywalls/${ID}/(?:source-access|preview-token)$`),
|
|
138
|
+
/* @__PURE__ */ new RegExp(`^/v2/campaigns/${ID}/audiences/${ID}/generate-rule$`),
|
|
139
|
+
/^\/v2\/demand-score\/(?:ai-report|launch-experiment)$/,
|
|
140
|
+
/^\/v2\/retention-onboarding\/(?:sandbox|production)(?:\/.*)?$/
|
|
141
|
+
];
|
|
142
|
+
const NARROWED = [
|
|
143
|
+
...[
|
|
144
|
+
"/v2/campaigns",
|
|
145
|
+
"/v2/surveys",
|
|
146
|
+
"/v2/retention-campaigns",
|
|
147
|
+
"/v2/retention-configurations",
|
|
148
|
+
"/v2/retention-default-messages",
|
|
149
|
+
"/v2/retention-messages"
|
|
150
|
+
].flatMap((prefix) => [{
|
|
151
|
+
methods: READ,
|
|
152
|
+
path: under(prefix)
|
|
153
|
+
}, {
|
|
154
|
+
methods: WRITE,
|
|
155
|
+
path: under(prefix)
|
|
156
|
+
}]),
|
|
157
|
+
{
|
|
158
|
+
methods: READ,
|
|
159
|
+
path: /^\/v2\/retention-onboarding\/status$/
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
methods: READ,
|
|
163
|
+
path: under("/v2/users")
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
methods: POST,
|
|
167
|
+
path: /^\/v2\/users\/query$/
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
methods: READ,
|
|
171
|
+
path: under("/v3/users")
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
methods: READ,
|
|
175
|
+
path: /^\/v2\/onboarding\/context$/
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
methods: POST,
|
|
179
|
+
path: /^\/v2\/demand-score\/query$/
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
methods: READ,
|
|
183
|
+
path: under("/v2/charts")
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
methods: POST,
|
|
187
|
+
path: /^\/v2\/charts\/(?:data|filter-values|acquisition-cohort-report)$/
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
methods: READ,
|
|
191
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/applications/${ID}/.+$`)
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
methods: READ,
|
|
195
|
+
path: under("/v2/paywalls")
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
methods: WRITE,
|
|
199
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/paywalls/(?!templates(?:/|$))${ID}(?:/.*)?$`)
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
methods: READ,
|
|
203
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/products/(?!(?:app-store-connect|google-play|store-products|store-product-prices)(?:/|$))${ID}(?:/delete-impact)?$`)
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
methods: READ,
|
|
207
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/entitlements/${ID}(?:/.*)?$`)
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
methods: WRITE,
|
|
211
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/entitlements/${ID}(?:/.*)?$`)
|
|
212
|
+
},
|
|
213
|
+
{
|
|
214
|
+
methods: new Set([
|
|
215
|
+
"GET",
|
|
216
|
+
"HEAD",
|
|
217
|
+
"DELETE"
|
|
218
|
+
]),
|
|
219
|
+
path: /* @__PURE__ */ new RegExp(`^/v2/assets/(?!(?:discover|upload-url)$)${ID}$`)
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
methods: POST,
|
|
223
|
+
path: /^\/v2\/assets\/upload-url$/
|
|
224
|
+
}
|
|
225
|
+
];
|
|
226
|
+
const MOUNT = /^\/dash-api(?=\/v[23](?:\/|$))/;
|
|
227
|
+
const QUERY_START = /[?;#]/;
|
|
228
|
+
const ORIGIN = /^https?:\/\/.*?\//;
|
|
229
|
+
const routedPath = (target) => {
|
|
230
|
+
return (target.charCodeAt(0) === 47 ? target : target.replace(ORIGIN, "/")).split(QUERY_START, 1)[0];
|
|
231
|
+
};
|
|
232
|
+
const normalizedPath = (target) => {
|
|
233
|
+
const path$1 = routedPath(target).toLowerCase().replace(/\/{2,}/g, "/").replace(MOUNT, "");
|
|
234
|
+
return path$1.length > 1 && path$1.endsWith("/") ? path$1.replace(/\/+$/, "") : path$1;
|
|
235
|
+
};
|
|
236
|
+
const pathSpellings = (target) => {
|
|
237
|
+
const path$1 = routedPath(target);
|
|
238
|
+
const raw = normalizedPath(path$1);
|
|
239
|
+
try {
|
|
240
|
+
const decoded = normalizedPath(decodeURIComponent(path$1));
|
|
241
|
+
return decoded === raw ? [raw] : [raw, decoded];
|
|
242
|
+
} catch {
|
|
243
|
+
return [raw];
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const isAllowedPath = (method, path$1, narrowed) => !DENIED.some((pattern) => pattern.test(path$1)) && ALLOWED.some((rule) => rule.methods.has(method) && rule.path.test(path$1)) && (!narrowed || NARROWED.some((rule) => rule.methods.has(method) && rule.path.test(path$1)));
|
|
247
|
+
const isWorkspaceRequestAllowed = (method, target, narrowed) => {
|
|
248
|
+
const normalized = method.toUpperCase();
|
|
249
|
+
return pathSpellings(target).every((path$1) => isAllowedPath(normalized, path$1, narrowed));
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
//#endregion
|
|
253
|
+
//#region src/core/workspaces/scopes.ts
|
|
254
|
+
const READ_FAMILIES = [
|
|
255
|
+
[/^\/v2\/organizations\/[^/]+\/query$/, "data:read"],
|
|
256
|
+
[/^\/v2\/projects\/[^/]+\/custom-stores(\/|$)/, "custom_stores:read"],
|
|
257
|
+
[/^\/v2\/projects(\/|$)/, "projects:read"],
|
|
258
|
+
[/^\/v2\/applications(\/|$)/, "applications:read"],
|
|
259
|
+
[/^\/v2\/paywalls(\/|$)/, "paywalls:read"],
|
|
260
|
+
[/^\/v2\/campaigns(\/|$)/, "campaigns:read"],
|
|
261
|
+
[/^\/v2\/products(\/|$)/, "products:read"],
|
|
262
|
+
[/^\/v2\/entitlements(\/|$)/, "entitlements:read"],
|
|
263
|
+
[/^\/v2\/assets(\/|$)/, "assets:read"],
|
|
264
|
+
[/^\/v2\/surveys(\/|$)/, "surveys:read"],
|
|
265
|
+
[/^\/v2\/retention-(campaigns|configurations|default-messages|messages)(\/|$)/, "retention_messages:read"],
|
|
266
|
+
[/^\/v2\/(charts|demand-score)(\/|$)/, "charts:read"],
|
|
267
|
+
[/^\/v[23]\/users(\/|$)/, "users:read"],
|
|
268
|
+
[/^\/v2\/onboarding(\/|$)/, "onboarding:read"]
|
|
269
|
+
];
|
|
270
|
+
const READ_POSTS = /^\/v2\/(organizations\/[^/]+\/query|charts\/(data|filter-values|acquisition-cohort-report)|users\/query|demand-score\/query)$/;
|
|
271
|
+
function scopeForRoute(method, pathname) {
|
|
272
|
+
if (method !== "GET" && method !== "HEAD" && !(method === "POST" && READ_POSTS.test(pathname))) return void 0;
|
|
273
|
+
return READ_FAMILIES.find(([route]) => route.test(pathname))?.[1];
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
//#endregion
|
|
277
|
+
//#region src/core/workspaces/dev/outbound.ts
|
|
278
|
+
const FORWARDED_HEADERS = [
|
|
279
|
+
"accept",
|
|
280
|
+
"accept-encoding",
|
|
281
|
+
"accept-language",
|
|
282
|
+
"content-type",
|
|
283
|
+
"if-match",
|
|
284
|
+
"if-none-match",
|
|
285
|
+
"idempotency-key",
|
|
286
|
+
"user-agent"
|
|
287
|
+
];
|
|
288
|
+
const EXPIRED_REASON = "agent_token_expired";
|
|
289
|
+
const refusalOf = async (answer) => {
|
|
290
|
+
const text = await answer.clone().text();
|
|
291
|
+
try {
|
|
292
|
+
const parsed = JSON.parse(text);
|
|
293
|
+
if (typeof parsed === "object" && parsed !== null) return parsed;
|
|
294
|
+
} catch {}
|
|
295
|
+
return { message: text };
|
|
296
|
+
};
|
|
297
|
+
const ORGANIZATION_QUERY = /^\/v2\/organizations\/[^/]+\/query\/?$/i;
|
|
298
|
+
const refuse = (status, message) => new Response(JSON.stringify({ message }), {
|
|
299
|
+
status,
|
|
300
|
+
headers: { "content-type": "application/json" }
|
|
301
|
+
});
|
|
302
|
+
const refuseRoute = () => new Response(JSON.stringify({
|
|
303
|
+
type: "permission_error",
|
|
304
|
+
code: "insufficient_permissions",
|
|
305
|
+
message: WORKSPACE_ROUTE_REFUSAL
|
|
306
|
+
}), {
|
|
307
|
+
status: 403,
|
|
308
|
+
headers: { "content-type": "application/json" }
|
|
309
|
+
});
|
|
310
|
+
const routeHint = (pathname, narrowed) => {
|
|
311
|
+
if (!narrowed) return "It answers the same on the real runtime.";
|
|
312
|
+
if (ORGANIZATION_QUERY.test(pathname)) return "A slot tied to one app can't run SQL: the organization query endpoint needs org.page@1 or a metric. It answers the same on the real runtime.";
|
|
313
|
+
return "This slot is tied to one app, and only reaches that app's routes. It answers the same on the real runtime, so use an org.page@1 or another route.";
|
|
314
|
+
};
|
|
315
|
+
const STRIPPED_ANSWER_HEADERS = [
|
|
316
|
+
"set-cookie",
|
|
317
|
+
"content-encoding",
|
|
318
|
+
"content-length",
|
|
319
|
+
"transfer-encoding"
|
|
320
|
+
];
|
|
321
|
+
const BODYLESS_STATUSES = new Set([
|
|
322
|
+
101,
|
|
323
|
+
204,
|
|
324
|
+
205,
|
|
325
|
+
304
|
|
326
|
+
]);
|
|
327
|
+
function rebuildResponse(answer, ResponseClass = Response, headers = answer.headers) {
|
|
328
|
+
return new ResponseClass(BODYLESS_STATUSES.has(answer.status) ? null : answer.body, {
|
|
329
|
+
status: answer.status,
|
|
330
|
+
headers
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
function createOutbound({ apiOrigin, credential, log, declaredScopes, limitedTo, fetchImpl = fetch }) {
|
|
334
|
+
const warnedScopes = /* @__PURE__ */ new Set();
|
|
335
|
+
const send = async (url, request, body, token) => {
|
|
336
|
+
const headers = new Headers();
|
|
337
|
+
for (const name of FORWARDED_HEADERS) {
|
|
338
|
+
const value = request.headers.get(name);
|
|
339
|
+
if (value !== null) headers.set(name, value);
|
|
340
|
+
}
|
|
341
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
342
|
+
return fetchImpl(url, {
|
|
343
|
+
method: request.method,
|
|
344
|
+
headers,
|
|
345
|
+
redirect: "manual",
|
|
346
|
+
...body ? { body } : {}
|
|
347
|
+
});
|
|
348
|
+
};
|
|
349
|
+
return async (request, caller) => {
|
|
350
|
+
const url = new URL(request.url);
|
|
351
|
+
if (url.hostname === PLATFORM_HOST) {
|
|
352
|
+
log.warn("Workspace storage, jobs and logs aren't available in dev.");
|
|
353
|
+
return refuse(501, "Workspace storage, jobs and logs aren't available in dev.");
|
|
354
|
+
}
|
|
355
|
+
if (url.hostname !== API_HOST) {
|
|
356
|
+
log.warn(`Refused ${request.method} ${url.origin}: dev runs like a draft, with no outside hosts.`);
|
|
357
|
+
return refuse(403, `Dev runs like a draft, with no outside hosts: ${url.hostname} isn't reachable.`);
|
|
358
|
+
}
|
|
359
|
+
const label = `${request.method} ${url.pathname}`;
|
|
360
|
+
if (!isWorkspaceRequestAllowed(request.method, `${url.pathname}${url.search}`, caller.narrowed)) {
|
|
361
|
+
log.warn(`${label} 403. ${WORKSPACE_ROUTE_REFUSAL} ${routeHint(url.pathname, caller.narrowed)}`);
|
|
362
|
+
return refuseRoute();
|
|
363
|
+
}
|
|
364
|
+
const scope = scopeForRoute(request.method, url.pathname);
|
|
365
|
+
if (scope !== void 0 && !declaredScopes().includes(scope) && !warnedScopes.has(scope)) {
|
|
366
|
+
warnedScopes.add(scope);
|
|
367
|
+
log.warn(`${label} needs ${scope}, which superwall.json doesn't declare. It answers 403 on the real runtime; add it to scopes.`);
|
|
368
|
+
}
|
|
369
|
+
const target = `${apiOrigin}${url.pathname}${url.search}`;
|
|
370
|
+
const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.arrayBuffer();
|
|
371
|
+
const started = Date.now();
|
|
372
|
+
const token = await credential.current();
|
|
373
|
+
let answer = await send(target, request, body, token);
|
|
374
|
+
if (answer.status === 401) {
|
|
375
|
+
const expired = (await refusalOf(answer)).reason === EXPIRED_REASON;
|
|
376
|
+
const renewed = await credential.renew(token, { expired }).catch((error) => {
|
|
377
|
+
log.warn(error.message);
|
|
378
|
+
});
|
|
379
|
+
if (renewed !== void 0) answer = await send(target, request, body, renewed);
|
|
380
|
+
}
|
|
381
|
+
const took = Date.now() - started;
|
|
382
|
+
if (answer.status === 403) {
|
|
383
|
+
const { message } = await refusalOf(answer);
|
|
384
|
+
const organization = limitedTo?.();
|
|
385
|
+
const reach = organization === void 0 ? "Dev is read-only." : `Dev's token is read-only, limited to organization ${organization} and the routes a workspace can read.`;
|
|
386
|
+
log.warn(`${label} ${answer.status} ${took}ms. ${reach} ${String(message ?? "").slice(0, 200)}`.trimEnd());
|
|
387
|
+
} else log.info(`${label} ${answer.status} ${took}ms`);
|
|
388
|
+
const headers = new Headers(answer.headers);
|
|
389
|
+
for (const name of STRIPPED_ANSWER_HEADERS) headers.delete(name);
|
|
390
|
+
return rebuildResponse(answer, Response, headers);
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
//#endregion
|
|
395
|
+
//#region src/core/workspaces/dev/runtime.ts
|
|
396
|
+
const INVOKE_PATH = "/__sw/invoke/";
|
|
397
|
+
const NARROWED_HEADER = "x-superwall-workspace-dev-narrowed";
|
|
398
|
+
const INVOCABLE = ["metric", "readout"];
|
|
399
|
+
const SANDBOX_MODULE = "delete globalThis.caches\n";
|
|
400
|
+
const MAIN_MODULE = `import "./sandbox.mjs"
|
|
401
|
+
import { WorkerEntrypoint } from "cloudflare:workers"
|
|
402
|
+
import handlers from "./worker.mjs"
|
|
403
|
+
export * from "./worker.mjs"
|
|
404
|
+
export default class Workspace extends WorkerEntrypoint {
|
|
405
|
+
fetch(request) {
|
|
406
|
+
return handlers.fetch(request)
|
|
407
|
+
}
|
|
408
|
+
metric(request) {
|
|
409
|
+
if (typeof handlers.metric !== "function") {
|
|
410
|
+
throw new Error("This workspace has no metric handler")
|
|
411
|
+
}
|
|
412
|
+
return handlers.metric(request)
|
|
413
|
+
}
|
|
414
|
+
readout(request) {
|
|
415
|
+
if (typeof handlers.readout !== "function") {
|
|
416
|
+
throw new Error("This workspace has no readout handler")
|
|
417
|
+
}
|
|
418
|
+
return handlers.readout(request)
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
`;
|
|
422
|
+
const HOST_MODULE = `import { WorkerEntrypoint } from "cloudflare:workers"
|
|
423
|
+
const json = (body, status) =>
|
|
424
|
+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } })
|
|
425
|
+
export class Egress extends WorkerEntrypoint {
|
|
426
|
+
fetch(request) {
|
|
427
|
+
return (this.ctx.props.narrowed ? this.env.EGRESS_APP : this.env.EGRESS).fetch(request)
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
const load = (env, exports, narrowed) =>
|
|
431
|
+
env.LOADER.get(narrowed ? "app" : "organization", () => ({
|
|
432
|
+
compatibilityDate: env.COMPATIBILITY_DATE,
|
|
433
|
+
compatibilityFlags: env.COMPATIBILITY_FLAGS,
|
|
434
|
+
mainModule: "platform.mjs",
|
|
435
|
+
modules: {
|
|
436
|
+
"platform.mjs": { js: ${JSON.stringify(MAIN_MODULE)} },
|
|
437
|
+
"sandbox.mjs": { js: ${JSON.stringify(SANDBOX_MODULE)} },
|
|
438
|
+
"worker.mjs": { js: env.CUSTOMER_MODULE },
|
|
439
|
+
},
|
|
440
|
+
env: {},
|
|
441
|
+
globalOutbound: exports.Egress({ props: { narrowed } }),
|
|
442
|
+
}))
|
|
443
|
+
export default {
|
|
444
|
+
async fetch(request, env, ctx) {
|
|
445
|
+
const narrowed = request.headers.get(${JSON.stringify(NARROWED_HEADER)}) === "1"
|
|
446
|
+
const { pathname } = new URL(request.url)
|
|
447
|
+
const workspace = load(env, ctx.exports, narrowed).getEntrypoint()
|
|
448
|
+
if (pathname.startsWith(${JSON.stringify(INVOKE_PATH)})) {
|
|
449
|
+
const kind = pathname.slice(13)
|
|
450
|
+
if (!${JSON.stringify(INVOCABLE)}.includes(kind)) return json({ error: "Not found." }, 404)
|
|
451
|
+
try {
|
|
452
|
+
return json({ result: await workspace[kind](await request.json()) }, 200)
|
|
453
|
+
} catch (error) {
|
|
454
|
+
return json({ error: String(error?.message ?? error) }, 500)
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
const headers = new Headers(request.headers)
|
|
458
|
+
headers.delete(${JSON.stringify(NARROWED_HEADER)})
|
|
459
|
+
try {
|
|
460
|
+
return await workspace.fetch(new Request(request, { headers }))
|
|
461
|
+
} catch (error) {
|
|
462
|
+
return new Response(String(error?.message ?? error), { status: 502 })
|
|
463
|
+
}
|
|
464
|
+
},
|
|
465
|
+
}
|
|
466
|
+
`;
|
|
467
|
+
const DEFAULT_COMPATIBILITY = {
|
|
468
|
+
date: WORKSPACE_COMPATIBILITY_DATE,
|
|
469
|
+
flags: []
|
|
470
|
+
};
|
|
471
|
+
const workerOptions = (module, compatibility = DEFAULT_COMPATIBILITY) => ({
|
|
472
|
+
name: "workspace-host",
|
|
473
|
+
compatibilityDate: WORKSPACE_COMPATIBILITY_DATE,
|
|
474
|
+
modules: [{
|
|
475
|
+
type: "ESModule",
|
|
476
|
+
path: "host.mjs",
|
|
477
|
+
contents: HOST_MODULE
|
|
478
|
+
}],
|
|
479
|
+
bindings: {
|
|
480
|
+
CUSTOMER_MODULE: module,
|
|
481
|
+
COMPATIBILITY_DATE: compatibility.date,
|
|
482
|
+
COMPATIBILITY_FLAGS: compatibility.flags
|
|
483
|
+
},
|
|
484
|
+
workerLoaders: { LOADER: {} }
|
|
485
|
+
});
|
|
486
|
+
const startMiniflare = async ({ root, module, compatibility, outbound }) => {
|
|
487
|
+
const { Miniflare, Response: RuntimeResponse, convertV4MiniflareOptions = (options$1) => options$1 } = await import(pathToFileURL(createRequire(resolveWranglerPackage(root)).resolve("miniflare")).href);
|
|
488
|
+
const egress = (caller) => async (request) => rebuildResponse(await outbound(request, caller), RuntimeResponse);
|
|
489
|
+
const options = (code, runsOn) => convertV4MiniflareOptions({ workers: [{
|
|
490
|
+
...workerOptions(code, runsOn),
|
|
491
|
+
serviceBindings: {
|
|
492
|
+
EGRESS: egress({ narrowed: false }),
|
|
493
|
+
EGRESS_APP: egress({ narrowed: true })
|
|
494
|
+
}
|
|
495
|
+
}] });
|
|
496
|
+
const miniflare = new Miniflare(options(module, compatibility));
|
|
497
|
+
try {
|
|
498
|
+
await miniflare.ready;
|
|
499
|
+
} catch (error) {
|
|
500
|
+
await miniflare.dispose().catch(() => {});
|
|
501
|
+
throw new WorkspaceError(`The workspace didn't start: ${error.message}\nIf the runtime says the compatibility date is too new, update wrangler with \`npm install -D wrangler@latest\`.`);
|
|
502
|
+
}
|
|
503
|
+
return {
|
|
504
|
+
fetch: (url, init, caller) => {
|
|
505
|
+
const headers = new Headers(init.headers);
|
|
506
|
+
if (caller?.narrowed) headers.set(NARROWED_HEADER, "1");
|
|
507
|
+
return miniflare.dispatchFetch(url, {
|
|
508
|
+
...init,
|
|
509
|
+
headers,
|
|
510
|
+
redirect: "manual"
|
|
511
|
+
});
|
|
512
|
+
},
|
|
513
|
+
update: (code, runsOn) => miniflare.setOptions(options(code, runsOn)),
|
|
514
|
+
dispose: () => miniflare.dispose()
|
|
515
|
+
};
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
//#endregion
|
|
519
|
+
//#region src/core/workspaces/dev/host-page.ts
|
|
520
|
+
const LIGHT_TOKENS = {
|
|
521
|
+
background: "#ffffff",
|
|
522
|
+
foreground: "#14151a",
|
|
523
|
+
card: "#ffffff",
|
|
524
|
+
"card-foreground": "#14151a",
|
|
525
|
+
popover: "#ffffff",
|
|
526
|
+
muted: "#f1f1f3",
|
|
527
|
+
"muted-foreground": "#6b6d76",
|
|
528
|
+
border: "#e4e4e8",
|
|
529
|
+
primary: "#74f8f0",
|
|
530
|
+
"primary-foreground": "#14151a",
|
|
531
|
+
secondary: "#f1f1f3",
|
|
532
|
+
"secondary-foreground": "#14151a",
|
|
533
|
+
destructive: "#d92d20",
|
|
534
|
+
success: "#12805c",
|
|
535
|
+
warning: "#b54708",
|
|
536
|
+
info: "#2563eb",
|
|
537
|
+
"fg-secondary": "#44464f",
|
|
538
|
+
"fg-tertiary": "#6b6d76",
|
|
539
|
+
radius: "3px"
|
|
540
|
+
};
|
|
541
|
+
const DARK_TOKENS = {
|
|
542
|
+
background: "#14151a",
|
|
543
|
+
foreground: "#f4f4f6",
|
|
544
|
+
card: "#1b1c22",
|
|
545
|
+
"card-foreground": "#f4f4f6",
|
|
546
|
+
popover: "#1b1c22",
|
|
547
|
+
muted: "#25262d",
|
|
548
|
+
"muted-foreground": "#9a9ca6",
|
|
549
|
+
border: "#2e2f37",
|
|
550
|
+
primary: "#74f8f0",
|
|
551
|
+
"primary-foreground": "#14151a",
|
|
552
|
+
secondary: "#25262d",
|
|
553
|
+
"secondary-foreground": "#f4f4f6",
|
|
554
|
+
destructive: "#f97066",
|
|
555
|
+
success: "#47cd89",
|
|
556
|
+
warning: "#fdb022",
|
|
557
|
+
info: "#60a5fa",
|
|
558
|
+
"fg-secondary": "#c9cad1",
|
|
559
|
+
"fg-tertiary": "#9a9ca6",
|
|
560
|
+
radius: "3px"
|
|
561
|
+
};
|
|
562
|
+
const STYLES = `
|
|
563
|
+
:root { color-scheme: light dark; }
|
|
564
|
+
* { box-sizing: border-box; }
|
|
565
|
+
body { margin: 0; height: 100vh; display: grid; grid-template-columns: 280px 1fr; font: 13px/1.5 system-ui, sans-serif; background: var(--background); color: var(--foreground); }
|
|
566
|
+
aside { border-right: 1px solid var(--border); padding: 16px; overflow: auto; display: flex; flex-direction: column; gap: 16px; }
|
|
567
|
+
main { display: flex; flex-direction: column; min-width: 0; min-height: 0; height: 100vh; }
|
|
568
|
+
h1 { font-size: 14px; font-weight: 600; margin: 0; }
|
|
569
|
+
h2 { font-size: 12px; font-weight: 500; color: var(--muted-foreground); margin: 0 0 6px; }
|
|
570
|
+
label { display: block; margin-bottom: 8px; color: var(--muted-foreground); }
|
|
571
|
+
input, select { display: block; width: 100%; margin-top: 2px; padding: 5px 6px; font: inherit; color: var(--foreground); background: var(--background); border: 1px solid var(--border); border-radius: var(--radius); }
|
|
572
|
+
button { padding: 5px 10px; font: inherit; color: var(--foreground); background: var(--muted); border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; }
|
|
573
|
+
.entry { display: block; width: 100%; text-align: left; margin-bottom: 4px; background: transparent; }
|
|
574
|
+
.entry[aria-current="true"] { background: var(--muted); }
|
|
575
|
+
.entry small { display: block; color: var(--muted-foreground); }
|
|
576
|
+
#stage { flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
|
|
577
|
+
iframe { width: 100%; border: 0; display: block; background: var(--background); }
|
|
578
|
+
iframe.fills { flex: 1; min-height: 100%; }
|
|
579
|
+
.panel { padding: 16px; }
|
|
580
|
+
.problem { padding: 16px; color: var(--destructive); white-space: pre-wrap; }
|
|
581
|
+
table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
|
|
582
|
+
th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid var(--border); }
|
|
583
|
+
th { font-weight: 500; color: var(--muted-foreground); }
|
|
584
|
+
svg { display: block; width: 100%; height: 160px; margin-bottom: 12px; }
|
|
585
|
+
#log { flex: none; height: 120px; overflow: auto; border-top: 1px solid var(--border); padding: 8px 16px; font: 12px/1.5 ui-monospace, monospace; color: var(--muted-foreground); }
|
|
586
|
+
.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; }
|
|
587
|
+
.row label { margin-bottom: 0; }
|
|
588
|
+
.row h1 { flex: 1; }
|
|
589
|
+
`;
|
|
590
|
+
const SCRIPT = `
|
|
591
|
+
const PROTOCOL = ${JSON.stringify(BRIDGE_PROTOCOL)};
|
|
592
|
+
const LOAD_TIMEOUT_MS = ${MOUNT_LOAD_TIMEOUT_MS};
|
|
593
|
+
const TOKENS = { light: ${JSON.stringify(LIGHT_TOKENS)}, dark: ${JSON.stringify(DARK_TOKENS)} };
|
|
594
|
+
const FIELD_LABELS = {
|
|
595
|
+
organizationId: "Organization id", applicationId: "App id", environment: "Environment", from: "From", to: "To",
|
|
596
|
+
campaignId: "Campaign id", audienceId: "Audience id", variantIds: "Variant ids, comma separated",
|
|
597
|
+
appUserId: "App user id", aliases: "Aliases, comma separated",
|
|
598
|
+
};
|
|
599
|
+
const el = (tag, attributes = {}, ...children) => {
|
|
600
|
+
const node = document.createElement(tag);
|
|
601
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
602
|
+
if (name.startsWith("on")) node.addEventListener(name.slice(2), value);
|
|
603
|
+
else if (value !== undefined && value !== null) node.setAttribute(name, value);
|
|
604
|
+
}
|
|
605
|
+
node.append(...children.filter((child) => child !== null && child !== undefined));
|
|
606
|
+
return node;
|
|
607
|
+
};
|
|
608
|
+
const $ = (id) => document.getElementById(id);
|
|
609
|
+
const post = async (path, body) => {
|
|
610
|
+
const response = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
611
|
+
const answer = await response.json();
|
|
612
|
+
if (!response.ok) throw new Error(answer.error ?? "Something went wrong.");
|
|
613
|
+
return answer;
|
|
614
|
+
};
|
|
615
|
+
const log = (text) => {
|
|
616
|
+
const line = el("div", {}, new Date().toLocaleTimeString() + " " + text);
|
|
617
|
+
$("log").append(line);
|
|
618
|
+
line.scrollIntoView({ block: "nearest" });
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
let state;
|
|
622
|
+
let selected;
|
|
623
|
+
let mode = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
|
624
|
+
let values = {};
|
|
625
|
+
let frame = null;
|
|
626
|
+
let mount = null;
|
|
627
|
+
let selection = 0;
|
|
628
|
+
|
|
629
|
+
const theme = () => ({ mode, tokens: TOKENS[mode] });
|
|
630
|
+
const applyTheme = () => {
|
|
631
|
+
for (const [name, value] of Object.entries(TOKENS[mode])) document.documentElement.style.setProperty("--" + name, value);
|
|
632
|
+
document.documentElement.style.colorScheme = mode;
|
|
633
|
+
};
|
|
634
|
+
const hostMessage = (body) => ({ ...body, protocol: PROTOCOL, nonce: mount.nonce });
|
|
635
|
+
const send = (body) => {
|
|
636
|
+
if (mount?.connected) frame?.contentWindow?.postMessage(hostMessage(body), mount.origin);
|
|
637
|
+
};
|
|
638
|
+
const fieldsOf = (slot) => {
|
|
639
|
+
const fields = state.slots[slot]?.fields ?? [];
|
|
640
|
+
return fields.flatMap((field) => (field === "dateRange" ? ["from", "to"] : [field]));
|
|
641
|
+
};
|
|
642
|
+
const inputFromForm = () => {
|
|
643
|
+
const input = { ...values };
|
|
644
|
+
for (const key of ["variantIds", "aliases"]) {
|
|
645
|
+
if (typeof input[key] === "string") input[key] = input[key].split(",").map((value) => value.trim()).filter(Boolean);
|
|
646
|
+
}
|
|
647
|
+
return input;
|
|
648
|
+
};
|
|
649
|
+
const renderContext = (slot) => {
|
|
650
|
+
const box = $("context");
|
|
651
|
+
box.replaceChildren(el("h2", {}, "Context"));
|
|
652
|
+
for (const field of fieldsOf(slot)) {
|
|
653
|
+
const control = field === "environment"
|
|
654
|
+
? el("select", { onchange: (event) => { values[field] = event.target.value; } }, ...["PRODUCTION", "SANDBOX"].map((value) => el("option", value === (values[field] ?? "PRODUCTION") ? { selected: "" } : {}, value)))
|
|
655
|
+
: el("input", { value: Array.isArray(values[field]) ? values[field].join(", ") : values[field] ?? "", oninput: (event) => { values[field] = event.target.value; } });
|
|
656
|
+
box.append(el("label", {}, FIELD_LABELS[field] ?? field, control));
|
|
657
|
+
}
|
|
658
|
+
box.append(el("button", { onclick: () => show() }, "Apply"));
|
|
659
|
+
};
|
|
660
|
+
const fail = (message) => {
|
|
661
|
+
frame = null;
|
|
662
|
+
mount = null;
|
|
663
|
+
$("stage").replaceChildren(el("div", { class: "problem" }, message));
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
const showFrame = async (entrypoint, generation) => {
|
|
667
|
+
const session = await post("/__dev/sessions", { entrypoint: entrypoint.id, input: inputFromForm() });
|
|
668
|
+
if (generation !== selection) return;
|
|
669
|
+
const slot = state.slots[session.slot];
|
|
670
|
+
const fills = slot.shape === "page" || session.slot === "app.dashboard.widget@1";
|
|
671
|
+
const nonce = crypto.randomUUID().replaceAll("-", "");
|
|
672
|
+
mount = { nonce, origin: session.origin, connected: false, slot, ready: false, timer: 0 };
|
|
673
|
+
frame = el("iframe", {
|
|
674
|
+
class: fills ? "fills" : undefined,
|
|
675
|
+
title: entrypoint.title,
|
|
676
|
+
sandbox: "allow-scripts allow-same-origin allow-forms allow-popups",
|
|
677
|
+
src: session.connect_url,
|
|
678
|
+
onload: () => {
|
|
679
|
+
mount.connected = true;
|
|
680
|
+
frame.contentWindow.postMessage(hostMessage({ _tag: "connect", theme: theme(), context: session.context }), mount.origin);
|
|
681
|
+
clearTimeout(mount.timer);
|
|
682
|
+
mount.timer = setTimeout(() => {
|
|
683
|
+
if (!mount.ready) log("It didn't send ready within " + LOAD_TIMEOUT_MS / 1000 + " seconds. In the dashboard this shows as: This app couldn't load. Try again.");
|
|
684
|
+
}, LOAD_TIMEOUT_MS);
|
|
685
|
+
},
|
|
686
|
+
});
|
|
687
|
+
if (!fills && slot.minHeight) frame.style.height = slot.minHeight + "px";
|
|
688
|
+
$("stage").replaceChildren(frame);
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
window.addEventListener("message", (event) => {
|
|
692
|
+
if (!mount || !frame || event.source !== frame.contentWindow || event.origin !== mount.origin) return;
|
|
693
|
+
const message = event.data;
|
|
694
|
+
if (message?.protocol !== PROTOCOL || message.nonce !== mount.nonce) return;
|
|
695
|
+
if (message._tag === "ready") {
|
|
696
|
+
mount.ready = true;
|
|
697
|
+
log("ready");
|
|
698
|
+
send({ _tag: "visibility", visible: true });
|
|
699
|
+
} else if (message._tag === "resize") {
|
|
700
|
+
const { minHeight, maxHeight, shape } = mount.slot;
|
|
701
|
+
if (shape === "page" || maxHeight === null) return;
|
|
702
|
+
const height = Math.min(maxHeight, Math.max(minHeight, Math.round(message.height)));
|
|
703
|
+
if (!frame.classList.contains("fills")) frame.style.height = height + "px";
|
|
704
|
+
} else if (message._tag === "error") {
|
|
705
|
+
fail("It reported: " + message.message);
|
|
706
|
+
} else {
|
|
707
|
+
log(message._tag + " " + JSON.stringify({ ...message, _tag: undefined, protocol: undefined, nonce: undefined }));
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
const chart = (points) => {
|
|
712
|
+
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
|
713
|
+
if (points.length === 0) return svg;
|
|
714
|
+
const series = new Map();
|
|
715
|
+
for (const point of points) {
|
|
716
|
+
const name = point.breakdown ?? "All";
|
|
717
|
+
series.set(name, [...(series.get(name) ?? []), point]);
|
|
718
|
+
}
|
|
719
|
+
const times = points.map((point) => Date.parse(point.t));
|
|
720
|
+
const [minT, maxT] = [Math.min(...times), Math.max(...times)];
|
|
721
|
+
const maxV = Math.max(...points.map((point) => point.value), 0) || 1;
|
|
722
|
+
svg.setAttribute("viewBox", "0 0 1000 160");
|
|
723
|
+
svg.setAttribute("preserveAspectRatio", "none");
|
|
724
|
+
const colors = ["#2563eb", "#12805c", "#b54708", "#7c3aed", "#d92d20", "#0891b2"];
|
|
725
|
+
[...series.values()].forEach((list, index) => {
|
|
726
|
+
const path = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
|
|
727
|
+
const sorted = [...list].sort((a, b) => Date.parse(a.t) - Date.parse(b.t));
|
|
728
|
+
path.setAttribute("points", sorted.map((point) => {
|
|
729
|
+
const x = maxT === minT ? 500 : ((Date.parse(point.t) - minT) / (maxT - minT)) * 1000;
|
|
730
|
+
return x + "," + (155 - (point.value / maxV) * 150);
|
|
731
|
+
}).join(" "));
|
|
732
|
+
path.setAttribute("fill", "none");
|
|
733
|
+
path.setAttribute("stroke", colors[index % colors.length]);
|
|
734
|
+
path.setAttribute("stroke-width", "2");
|
|
735
|
+
path.setAttribute("vector-effect", "non-scaling-stroke");
|
|
736
|
+
svg.append(path);
|
|
737
|
+
});
|
|
738
|
+
return svg;
|
|
739
|
+
};
|
|
740
|
+
|
|
741
|
+
const showMetric = (entrypoint) => {
|
|
742
|
+
const definition = entrypoint.metric ?? {};
|
|
743
|
+
const query = { from: values.from ?? "", to: values.to ?? "", interval: "day", breakdown: "", filters: {} };
|
|
744
|
+
const out = el("div", {});
|
|
745
|
+
const run = async () => {
|
|
746
|
+
out.replaceChildren(el("p", {}, "Running..."));
|
|
747
|
+
try {
|
|
748
|
+
const { series, took_ms } = await post("/__dev/metric", {
|
|
749
|
+
entrypoint: entrypoint.id,
|
|
750
|
+
input: inputFromForm(),
|
|
751
|
+
from: query.from || undefined,
|
|
752
|
+
to: query.to || undefined,
|
|
753
|
+
interval: query.interval,
|
|
754
|
+
breakdown: query.breakdown || null,
|
|
755
|
+
filters: query.filters,
|
|
756
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
757
|
+
});
|
|
758
|
+
const rows = series.points.slice(0, 500).map((point) => el("tr", {}, el("td", {}, point.t), el("td", {}, point.breakdown ?? ""), el("td", {}, String(point.value))));
|
|
759
|
+
out.replaceChildren(
|
|
760
|
+
el("p", {}, series.points.length + " points in " + took_ms + " ms"),
|
|
761
|
+
chart(series.points),
|
|
762
|
+
el("table", {}, el("thead", {}, el("tr", {}, el("th", {}, "Bucket"), el("th", {}, "Breakdown"), el("th", {}, "Value"))), el("tbody", {}, ...rows)),
|
|
763
|
+
);
|
|
764
|
+
} catch (error) {
|
|
765
|
+
out.replaceChildren(el("div", { class: "problem" }, error.message));
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
const breakdowns = el("select", { onchange: (event) => { query.breakdown = event.target.value; } }, el("option", { value: "" }, "None"), ...(definition.breakdowns ?? []).map((item) => el("option", { value: item.key }, item.name)));
|
|
769
|
+
const filters = (definition.filters ?? []).map((filter) =>
|
|
770
|
+
el("label", {}, filter.name, el("select", { onchange: (event) => { query.filters[filter.key] = event.target.value ? [event.target.value] : []; } }, el("option", { value: "" }, "All"), ...filter.values.map((option) => el("option", { value: option.value }, option.label)))),
|
|
771
|
+
);
|
|
772
|
+
const form = el("div", { class: "row" },
|
|
773
|
+
el("label", {}, "From", el("input", { placeholder: "30 days ago", oninput: (event) => { query.from = event.target.value; } })),
|
|
774
|
+
el("label", {}, "To", el("input", { placeholder: "Now", oninput: (event) => { query.to = event.target.value; } })),
|
|
775
|
+
el("label", {}, "Interval", el("select", { onchange: (event) => { query.interval = event.target.value; } }, ...["day", "hour", "week", "month"].map((value) => el("option", {}, value)))),
|
|
776
|
+
el("label", {}, "Breakdown", breakdowns),
|
|
777
|
+
...filters,
|
|
778
|
+
el("button", { onclick: run }, "Run"),
|
|
779
|
+
);
|
|
780
|
+
$("stage").replaceChildren(el("div", { class: "panel" }, el("h1", {}, entrypoint.title), el("p", {}, definition.description ?? ""), form, out));
|
|
781
|
+
frame = null;
|
|
782
|
+
mount = null;
|
|
783
|
+
if (values.applicationId) run();
|
|
784
|
+
};
|
|
785
|
+
|
|
786
|
+
const showReadout = (entrypoint) => {
|
|
787
|
+
const out = el("div", {});
|
|
788
|
+
const run = async () => {
|
|
789
|
+
try {
|
|
790
|
+
const { result, took_ms } = await post("/__dev/readout", { entrypoint: entrypoint.id, input: inputFromForm() });
|
|
791
|
+
const rows = result.variants.map((variant) => el("tr", {}, el("td", {}, String(variant.variantId)), el("td", {}, String(variant.value)), el("td", {}, variant.interval ? variant.interval.join(" to ") : "")));
|
|
792
|
+
out.replaceChildren(el("p", {}, took_ms + " ms"), el("table", {}, el("thead", {}, el("tr", {}, el("th", {}, "Variant"), el("th", {}, "Value"), el("th", {}, "Interval"))), el("tbody", {}, ...rows)));
|
|
793
|
+
} catch (error) {
|
|
794
|
+
out.replaceChildren(el("div", { class: "problem" }, error.message));
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
$("stage").replaceChildren(el("div", { class: "panel" }, el("h1", {}, entrypoint.title), el("button", { onclick: run }, "Run"), out));
|
|
798
|
+
frame = null;
|
|
799
|
+
mount = null;
|
|
800
|
+
};
|
|
801
|
+
|
|
802
|
+
const show = async () => {
|
|
803
|
+
const entrypoint = state.manifest.entrypoints.find((candidate) => candidate.id === selected);
|
|
804
|
+
if (!entrypoint) return;
|
|
805
|
+
selection += 1;
|
|
806
|
+
const generation = selection;
|
|
807
|
+
try {
|
|
808
|
+
if (entrypoint.slot === "chart.source@1") showMetric(entrypoint);
|
|
809
|
+
else if (entrypoint.slot === "campaign.metric@1") showReadout(entrypoint);
|
|
810
|
+
else await showFrame(entrypoint, generation);
|
|
811
|
+
} catch (error) {
|
|
812
|
+
if (generation === selection) fail(error.message);
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
const select = (id) => {
|
|
816
|
+
selected = id;
|
|
817
|
+
const entrypoint = state.manifest.entrypoints.find((candidate) => candidate.id === id);
|
|
818
|
+
for (const button of document.querySelectorAll(".entry")) button.setAttribute("aria-current", String(button.dataset.id === id));
|
|
819
|
+
renderContext(entrypoint.slot);
|
|
820
|
+
history.replaceState(null, "", "#" + id);
|
|
821
|
+
show();
|
|
822
|
+
};
|
|
823
|
+
const renderEntrypoints = () => {
|
|
824
|
+
const box = $("entrypoints");
|
|
825
|
+
box.replaceChildren(el("h2", {}, "Entrypoints"));
|
|
826
|
+
for (const entrypoint of state.manifest.entrypoints) {
|
|
827
|
+
const button = el("button", { class: "entry", onclick: () => select(entrypoint.id) }, entrypoint.title, el("small", {}, entrypoint.slot));
|
|
828
|
+
button.dataset.id = entrypoint.id;
|
|
829
|
+
box.append(button);
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
const load = async () => {
|
|
833
|
+
state = await (await fetch("/__dev/state")).json();
|
|
834
|
+
values = { ...state.defaults, ...values };
|
|
835
|
+
$("title").textContent = state.manifest.name;
|
|
836
|
+
renderEntrypoints();
|
|
837
|
+
const wanted = location.hash.slice(1);
|
|
838
|
+
const first = state.manifest.entrypoints.find((candidate) => candidate.id === wanted) ?? state.manifest.entrypoints[0];
|
|
839
|
+
if (first) select(first.id);
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
$("theme").addEventListener("click", () => {
|
|
843
|
+
mode = mode === "dark" ? "light" : "dark";
|
|
844
|
+
applyTheme();
|
|
845
|
+
send({ _tag: "theme", theme: theme() });
|
|
846
|
+
});
|
|
847
|
+
const events = new EventSource("/__dev/events");
|
|
848
|
+
events.onmessage = (event) => {
|
|
849
|
+
const message = JSON.parse(event.data);
|
|
850
|
+
if (message.type === "error") {
|
|
851
|
+
log(message.message);
|
|
852
|
+
fail(message.message);
|
|
853
|
+
} else {
|
|
854
|
+
log("Rebuilt");
|
|
855
|
+
load();
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
applyTheme();
|
|
859
|
+
load();
|
|
860
|
+
`;
|
|
861
|
+
function renderHostPage() {
|
|
862
|
+
return `<!doctype html>
|
|
863
|
+
<html lang="en">
|
|
864
|
+
<head>
|
|
865
|
+
<meta charset="utf-8" />
|
|
866
|
+
<title>Workspace dev</title>
|
|
867
|
+
<style>${STYLES}</style>
|
|
868
|
+
</head>
|
|
869
|
+
<body>
|
|
870
|
+
<aside>
|
|
871
|
+
<div class="row"><h1 id="title">Workspace</h1><button id="theme">Theme</button></div>
|
|
872
|
+
<div id="entrypoints"></div>
|
|
873
|
+
<div id="context"></div>
|
|
874
|
+
</aside>
|
|
875
|
+
<main>
|
|
876
|
+
<div id="stage"></div>
|
|
877
|
+
<div id="log" aria-label="Log"></div>
|
|
878
|
+
</main>
|
|
879
|
+
<script>${SCRIPT}<\/script>
|
|
880
|
+
</body>
|
|
881
|
+
</html>`;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
//#endregion
|
|
885
|
+
//#region src/core/workspaces/dev/server.ts
|
|
886
|
+
const readBody = (request) => new Promise((resolve$1, reject) => {
|
|
887
|
+
const chunks = [];
|
|
888
|
+
request.on("data", (chunk) => chunks.push(chunk));
|
|
889
|
+
request.on("end", () => resolve$1(Buffer.concat(chunks)));
|
|
890
|
+
request.on("error", reject);
|
|
891
|
+
});
|
|
892
|
+
const sendJson = (response, status, body) => {
|
|
893
|
+
response.writeHead(status, {
|
|
894
|
+
"content-type": "application/json",
|
|
895
|
+
"cache-control": "no-store"
|
|
896
|
+
});
|
|
897
|
+
response.end(JSON.stringify(body));
|
|
898
|
+
};
|
|
899
|
+
const listen = (server, port) => new Promise((resolve$1, reject) => {
|
|
900
|
+
server.once("error", (error) => {
|
|
901
|
+
reject(error.code === "EADDRINUSE" ? new WorkspaceError(`Port ${port} is already in use. Pick another with --port; dev also takes the one after it.`) : error);
|
|
902
|
+
});
|
|
903
|
+
server.listen(port, "127.0.0.1", () => {
|
|
904
|
+
const address = server.address();
|
|
905
|
+
resolve$1(typeof address === "object" && address !== null ? address.port : port);
|
|
906
|
+
});
|
|
907
|
+
});
|
|
908
|
+
const closeServer = (server) => new Promise((resolve$1) => {
|
|
909
|
+
server.close(() => resolve$1());
|
|
910
|
+
server.closeAllConnections();
|
|
911
|
+
});
|
|
912
|
+
const customerPolicy = (hostOrigin) => [
|
|
913
|
+
"default-src 'self'",
|
|
914
|
+
"script-src 'self' 'unsafe-inline'",
|
|
915
|
+
"style-src 'self' 'unsafe-inline'",
|
|
916
|
+
"img-src 'self' data: blob:",
|
|
917
|
+
"font-src 'self' data:",
|
|
918
|
+
"media-src 'self' blob:",
|
|
919
|
+
"worker-src 'self' blob:",
|
|
920
|
+
"connect-src 'self'",
|
|
921
|
+
"frame-src 'self'",
|
|
922
|
+
`frame-ancestors ${hostOrigin}`,
|
|
923
|
+
"base-uri 'self'",
|
|
924
|
+
"object-src 'none'",
|
|
925
|
+
"form-action 'self'"
|
|
926
|
+
].join("; ");
|
|
927
|
+
const headerJson = (value) => JSON.stringify(value).replace(/[\u007f-]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
928
|
+
const withTimeout = async (work, ms, message) => {
|
|
929
|
+
let timer;
|
|
930
|
+
const timeout = new Promise((_, reject) => {
|
|
931
|
+
timer = setTimeout(() => reject(new WorkspaceError(message)), ms);
|
|
932
|
+
});
|
|
933
|
+
try {
|
|
934
|
+
return await Promise.race([work, timeout]);
|
|
935
|
+
} finally {
|
|
936
|
+
clearTimeout(timer);
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
const sessionTokenOf = (cookie, cookieName) => {
|
|
940
|
+
for (const part of (cookie ?? "").split(";")) {
|
|
941
|
+
const [name, value] = part.trim().split("=");
|
|
942
|
+
if (name === cookieName) return value;
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
const writeBody = async (answer, response) => {
|
|
946
|
+
if (answer.body === null) {
|
|
947
|
+
response.end();
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
const reader = answer.body.getReader();
|
|
951
|
+
response.once("close", () => void reader.cancel().catch(() => {}));
|
|
952
|
+
for (;;) {
|
|
953
|
+
const { done, value } = await reader.read();
|
|
954
|
+
if (done) break;
|
|
955
|
+
response.write(value);
|
|
956
|
+
}
|
|
957
|
+
response.end();
|
|
958
|
+
};
|
|
959
|
+
async function startDevServer(options) {
|
|
960
|
+
const { getManifest, runtime, defaults } = options;
|
|
961
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
962
|
+
const codes = /* @__PURE__ */ new Map();
|
|
963
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
964
|
+
let hostOrigin = "";
|
|
965
|
+
let frameOrigin = "";
|
|
966
|
+
let sessionCookie = "";
|
|
967
|
+
const invoke = async (kind, payload, timeoutMs) => {
|
|
968
|
+
const body = await (await withTimeout(runtime.fetch(`${frameOrigin}${INVOKE_PATH}${kind}`, {
|
|
969
|
+
method: "POST",
|
|
970
|
+
headers: { "content-type": "application/json" },
|
|
971
|
+
body: JSON.stringify(payload)
|
|
972
|
+
}), timeoutMs, `The ${kind} handler didn't answer within ${timeoutMs / 1e3} seconds.`)).json();
|
|
973
|
+
if (body.error !== void 0) throw new WorkspaceError(body.error);
|
|
974
|
+
return body.result;
|
|
975
|
+
};
|
|
976
|
+
const contextFor = (slot, input) => {
|
|
977
|
+
const context = buildContext(slot, {
|
|
978
|
+
...defaults,
|
|
979
|
+
...input
|
|
980
|
+
});
|
|
981
|
+
const { organizationId } = context;
|
|
982
|
+
if (defaults.organizationId !== void 0 && organizationId !== void 0 && String(organizationId) !== defaults.organizationId) throw new WorkspaceError(`This dev is running against organization ${defaults.organizationId}, and its token reaches only that one. Restart dev with --org ${String(organizationId)} to use ${String(organizationId)}.`);
|
|
983
|
+
return context;
|
|
984
|
+
};
|
|
985
|
+
const runMetric = async (call) => {
|
|
986
|
+
const entrypoint = findEntrypoint(getManifest(), call.entrypoint);
|
|
987
|
+
if (entrypoint.slot !== "chart.source@1") throw new WorkspaceError(`\`${entrypoint.id}\` (${entrypoint.slot}) isn't a metric.`);
|
|
988
|
+
const filters = Object.fromEntries(Object.entries(call.filters ?? {}).filter(([, values]) => values.length > 0));
|
|
989
|
+
checkMetricQuery(entrypoint.metric, {
|
|
990
|
+
breakdown: call.breakdown,
|
|
991
|
+
filters
|
|
992
|
+
});
|
|
993
|
+
const range = defaultRange(30);
|
|
994
|
+
const started = Date.now();
|
|
995
|
+
const series = await invoke("metric", {
|
|
996
|
+
metric: entrypoint.id,
|
|
997
|
+
context: contextFor(entrypoint.slot, call.input),
|
|
998
|
+
from: new Date(call.from ?? range.from).toISOString(),
|
|
999
|
+
to: new Date(call.to ?? range.to).toISOString(),
|
|
1000
|
+
interval: call.interval ?? "day",
|
|
1001
|
+
timezone: call.timezone ?? "UTC",
|
|
1002
|
+
breakdown: call.breakdown ?? null,
|
|
1003
|
+
filters
|
|
1004
|
+
}, METRIC_LIMITS.timeoutMs);
|
|
1005
|
+
const problem = seriesProblem(series);
|
|
1006
|
+
if (problem) throw new WorkspaceError(problem);
|
|
1007
|
+
return {
|
|
1008
|
+
series,
|
|
1009
|
+
took_ms: Date.now() - started
|
|
1010
|
+
};
|
|
1011
|
+
};
|
|
1012
|
+
const runReadout = async (call) => {
|
|
1013
|
+
const entrypoint = findEntrypoint(getManifest(), call.entrypoint);
|
|
1014
|
+
if (entrypoint.slot !== "campaign.metric@1") throw new WorkspaceError(`\`${entrypoint.id}\` (${entrypoint.slot}) isn't a readout.`);
|
|
1015
|
+
const context = contextFor(entrypoint.slot, call.input);
|
|
1016
|
+
const started = Date.now();
|
|
1017
|
+
const result = await invoke("readout", {
|
|
1018
|
+
metric: entrypoint.id,
|
|
1019
|
+
context
|
|
1020
|
+
}, READOUT_LIMITS.timeoutMs);
|
|
1021
|
+
const problem = readoutProblem(result, context.variantIds ?? []);
|
|
1022
|
+
if (problem) throw new WorkspaceError(problem);
|
|
1023
|
+
return {
|
|
1024
|
+
result,
|
|
1025
|
+
took_ms: Date.now() - started
|
|
1026
|
+
};
|
|
1027
|
+
};
|
|
1028
|
+
const createSession = (call) => {
|
|
1029
|
+
const entrypoint = findEntrypoint(getManifest(), call.entrypoint);
|
|
1030
|
+
if (entrypoint.path === void 0) throw new WorkspaceError(`\`${entrypoint.id}\` (${entrypoint.slot}) has no path to open.`);
|
|
1031
|
+
const context = contextFor(entrypoint.slot, call.input);
|
|
1032
|
+
const token = randomBytes(24).toString("hex");
|
|
1033
|
+
const code = randomBytes(24).toString("hex");
|
|
1034
|
+
sessions.set(token, {
|
|
1035
|
+
entrypointId: entrypoint.id,
|
|
1036
|
+
path: entrypoint.path,
|
|
1037
|
+
context,
|
|
1038
|
+
narrowed: entrypoint.slot !== "org.page@1"
|
|
1039
|
+
});
|
|
1040
|
+
codes.set(code, token);
|
|
1041
|
+
return {
|
|
1042
|
+
connect_url: `${frameOrigin}/__connect?code=${code}`,
|
|
1043
|
+
origin: frameOrigin,
|
|
1044
|
+
slot: entrypoint.slot,
|
|
1045
|
+
context
|
|
1046
|
+
};
|
|
1047
|
+
};
|
|
1048
|
+
const state = () => ({
|
|
1049
|
+
frameOrigin,
|
|
1050
|
+
defaults,
|
|
1051
|
+
slots: SLOTS,
|
|
1052
|
+
manifest: getManifest()
|
|
1053
|
+
});
|
|
1054
|
+
const allowedHost = (request, origin) => request.headers.host === new URL(origin).host;
|
|
1055
|
+
const answerHost = async (request, response) => {
|
|
1056
|
+
if (!allowedHost(request, hostOrigin)) return sendJson(response, 403, { error: "Open this through localhost." });
|
|
1057
|
+
const { pathname } = new URL(request.url ?? "/", hostOrigin);
|
|
1058
|
+
if (request.method === "GET" && pathname === "/") {
|
|
1059
|
+
response.writeHead(200, {
|
|
1060
|
+
"content-type": "text/html; charset=utf-8",
|
|
1061
|
+
"cache-control": "no-store"
|
|
1062
|
+
});
|
|
1063
|
+
response.end(renderHostPage());
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
if (request.method === "GET" && pathname === "/__dev/state") return sendJson(response, 200, state());
|
|
1067
|
+
if (request.method === "GET" && pathname === "/__dev/events") {
|
|
1068
|
+
response.writeHead(200, {
|
|
1069
|
+
"content-type": "text/event-stream",
|
|
1070
|
+
"cache-control": "no-store"
|
|
1071
|
+
});
|
|
1072
|
+
response.write(": connected\n\n");
|
|
1073
|
+
subscribers.add(response);
|
|
1074
|
+
request.on("close", () => subscribers.delete(response));
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
if (request.method !== "POST") return sendJson(response, 404, { error: "Not found." });
|
|
1078
|
+
if (request.headers.origin !== hostOrigin) return sendJson(response, 403, { error: `POSTs here need the header Origin: ${hostOrigin}.` });
|
|
1079
|
+
try {
|
|
1080
|
+
const body = JSON.parse((await readBody(request)).toString("utf8") || "{}");
|
|
1081
|
+
if (pathname === "/__dev/sessions") return sendJson(response, 200, createSession(body));
|
|
1082
|
+
if (pathname === "/__dev/metric") return sendJson(response, 200, await runMetric(body));
|
|
1083
|
+
if (pathname === "/__dev/readout") return sendJson(response, 200, await runReadout(body));
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
return sendJson(response, 400, { error: error.message });
|
|
1086
|
+
}
|
|
1087
|
+
sendJson(response, 404, { error: "Not found." });
|
|
1088
|
+
};
|
|
1089
|
+
const answerFrame = async (request, response) => {
|
|
1090
|
+
if (!allowedHost(request, frameOrigin)) return sendJson(response, 403, { error: "Open this through localhost." });
|
|
1091
|
+
const url = new URL(request.url ?? "/", frameOrigin);
|
|
1092
|
+
if (url.pathname === "/__connect") {
|
|
1093
|
+
const code = url.searchParams.get("code") ?? "";
|
|
1094
|
+
const token = codes.get(code);
|
|
1095
|
+
const session$1 = token === void 0 ? void 0 : sessions.get(token);
|
|
1096
|
+
codes.delete(code);
|
|
1097
|
+
if (session$1 === void 0) return sendJson(response, 400, { error: "That link was already used." });
|
|
1098
|
+
response.writeHead(302, {
|
|
1099
|
+
location: session$1.path,
|
|
1100
|
+
"set-cookie": `${sessionCookie}=${token}; Path=/; HttpOnly; SameSite=Lax`
|
|
1101
|
+
});
|
|
1102
|
+
response.end();
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
if (isInternalPath(url.pathname)) return sendJson(response, 404, { error: "Not found." });
|
|
1106
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1107
|
+
if (hasBody && request.headers.origin !== frameOrigin) return sendJson(response, 403, { error: "Only this frame's own page can send this." });
|
|
1108
|
+
const session = sessions.get(sessionTokenOf(request.headers.cookie, sessionCookie) ?? "");
|
|
1109
|
+
if (session === void 0) return sendJson(response, 401, { error: `This frame has no session. Open it from ${hostOrigin}.` });
|
|
1110
|
+
const headers = new Headers();
|
|
1111
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
1112
|
+
if (name === "cookie" || name === "host" || name.startsWith("mf-") || name.startsWith(WORKSPACE_HEADER_PREFIX)) continue;
|
|
1113
|
+
if (typeof value === "string") headers.set(name, value);
|
|
1114
|
+
}
|
|
1115
|
+
headers.set(CONTEXT_HEADER, headerJson(session.context));
|
|
1116
|
+
headers.set(ENTRYPOINT_HEADER, session.entrypointId);
|
|
1117
|
+
headers.set(TRIGGER_HEADER, "dev");
|
|
1118
|
+
const answer = await runtime.fetch(`${frameOrigin}${request.url}`, {
|
|
1119
|
+
method: request.method,
|
|
1120
|
+
headers,
|
|
1121
|
+
...hasBody ? { body: await readBody(request) } : {}
|
|
1122
|
+
}, { narrowed: session.narrowed });
|
|
1123
|
+
const out = new Headers(answer.headers);
|
|
1124
|
+
out.delete("set-cookie");
|
|
1125
|
+
out.delete("access-control-allow-credentials");
|
|
1126
|
+
out.delete("content-encoding");
|
|
1127
|
+
out.delete("content-length");
|
|
1128
|
+
out.delete("transfer-encoding");
|
|
1129
|
+
for (const name of [...out.keys()]) if (name.startsWith("mf-")) out.delete(name);
|
|
1130
|
+
out.append("content-security-policy", customerPolicy(hostOrigin));
|
|
1131
|
+
out.set("x-content-type-options", "nosniff");
|
|
1132
|
+
out.set("referrer-policy", "same-origin");
|
|
1133
|
+
response.writeHead(answer.status, Object.fromEntries(out.entries()));
|
|
1134
|
+
await writeBody(answer, response);
|
|
1135
|
+
};
|
|
1136
|
+
const guarded = (answer) => (request, response) => {
|
|
1137
|
+
answer(request, response).catch((error) => {
|
|
1138
|
+
if (response.headersSent) {
|
|
1139
|
+
response.end();
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
sendJson(response, 500, { error: error.message });
|
|
1143
|
+
});
|
|
1144
|
+
};
|
|
1145
|
+
const hostServer = http.createServer(guarded(answerHost));
|
|
1146
|
+
const frameServer = http.createServer(guarded(answerFrame));
|
|
1147
|
+
const hostPort = await listen(hostServer, options.port);
|
|
1148
|
+
const framePort = await listen(frameServer, options.port === 0 ? 0 : options.port + 1).catch(async (error) => {
|
|
1149
|
+
await closeServer(hostServer);
|
|
1150
|
+
throw error;
|
|
1151
|
+
});
|
|
1152
|
+
hostOrigin = `http://localhost:${hostPort}`;
|
|
1153
|
+
frameOrigin = `http://localhost:${framePort}`;
|
|
1154
|
+
sessionCookie = `sw_dev_session_${framePort}`;
|
|
1155
|
+
return {
|
|
1156
|
+
hostOrigin,
|
|
1157
|
+
frameOrigin,
|
|
1158
|
+
publish(event) {
|
|
1159
|
+
const line = `data: ${JSON.stringify(event)}\n\n`;
|
|
1160
|
+
for (const subscriber of subscribers) subscriber.write(line);
|
|
1161
|
+
},
|
|
1162
|
+
async close() {
|
|
1163
|
+
for (const subscriber of subscribers) subscriber.end();
|
|
1164
|
+
await Promise.all([closeServer(hostServer), closeServer(frameServer)]);
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
//#endregion
|
|
1170
|
+
//#region src/core/workspaces/dev/run.ts
|
|
1171
|
+
const UNWATCHED_DIRS = new Set(["node_modules", "dist"]);
|
|
1172
|
+
const UNWATCHED_FILES = new Set([WORKSPACE_FILE]);
|
|
1173
|
+
const DEBOUNCE_MS = 150;
|
|
1174
|
+
const TOKEN_TTL_SECONDS = 3600;
|
|
1175
|
+
const SOURCE_FILE = /\.(?:tsx?|jsx?|mts|mjs|cts|cjs|css|jsonc?|toml|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf)$/;
|
|
1176
|
+
const isWatched = (name) => !name.startsWith(".") && !UNWATCHED_DIRS.has(name) && !UNWATCHED_FILES.has(name);
|
|
1177
|
+
function watchProject(root, onChange) {
|
|
1178
|
+
let timer;
|
|
1179
|
+
const changed = () => {
|
|
1180
|
+
clearTimeout(timer);
|
|
1181
|
+
timer = setTimeout(onChange, DEBOUNCE_MS);
|
|
1182
|
+
};
|
|
1183
|
+
const nested = /* @__PURE__ */ new Map();
|
|
1184
|
+
const attach = (name) => {
|
|
1185
|
+
nested.get(name)?.close();
|
|
1186
|
+
nested.delete(name);
|
|
1187
|
+
const dir = path.join(root, name);
|
|
1188
|
+
if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) nested.set(name, fs.watch(dir, { recursive: true }, changed));
|
|
1189
|
+
};
|
|
1190
|
+
for (const name of fs.readdirSync(root).filter(isWatched)) attach(name);
|
|
1191
|
+
const top = fs.watch(root, (_event, file) => {
|
|
1192
|
+
if (file === null) changed();
|
|
1193
|
+
else if (isWatched(file)) {
|
|
1194
|
+
const wasFolder = nested.has(file);
|
|
1195
|
+
attach(file);
|
|
1196
|
+
if (wasFolder || nested.has(file) || SOURCE_FILE.test(file)) changed();
|
|
1197
|
+
}
|
|
1198
|
+
});
|
|
1199
|
+
return () => {
|
|
1200
|
+
clearTimeout(timer);
|
|
1201
|
+
top.close();
|
|
1202
|
+
for (const watcher of nested.values()) watcher.close();
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
function mintRefusal(error) {
|
|
1206
|
+
return /WorkOS access token/i.test(error.message) ? "`superwall workspaces dev` needs a browser login: it makes its read-only token from your session, and an API key can't. Run `superwall login`." : error.message;
|
|
1207
|
+
}
|
|
1208
|
+
function agentCredential(ctx, organizationId) {
|
|
1209
|
+
let limited = true;
|
|
1210
|
+
return {
|
|
1211
|
+
credential: createAgentCredential(async () => {
|
|
1212
|
+
try {
|
|
1213
|
+
const minted = await ctx.api.post("/v2/me/agent-token", {
|
|
1214
|
+
ttl_seconds: TOKEN_TTL_SECONDS,
|
|
1215
|
+
organization_id: Number(organizationId)
|
|
1216
|
+
});
|
|
1217
|
+
if (minted.organization_id === void 0 && limited) {
|
|
1218
|
+
limited = false;
|
|
1219
|
+
ctx.ui.warn("This API can't limit dev's token to one organization yet, so it reaches everything you can read.");
|
|
1220
|
+
}
|
|
1221
|
+
return minted.token;
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
if (error instanceof ApiError && error.status === 403) throw new WorkspaceError(mintRefusal(error));
|
|
1224
|
+
throw error;
|
|
1225
|
+
}
|
|
1226
|
+
}),
|
|
1227
|
+
limitedTo: () => limited ? organizationId : void 0
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
const waitForSignal = (stop) => new Promise((resolve$1) => {
|
|
1231
|
+
const finish = () => {
|
|
1232
|
+
process.off("SIGINT", finish);
|
|
1233
|
+
process.off("SIGTERM", finish);
|
|
1234
|
+
stop().finally(resolve$1);
|
|
1235
|
+
};
|
|
1236
|
+
process.once("SIGINT", finish);
|
|
1237
|
+
process.once("SIGTERM", finish);
|
|
1238
|
+
});
|
|
1239
|
+
async function resolveDefaults(ctx, input) {
|
|
1240
|
+
const context = {
|
|
1241
|
+
campaignId: input.campaign,
|
|
1242
|
+
audienceId: input.audience,
|
|
1243
|
+
variantIds: input.variant,
|
|
1244
|
+
appUserId: input.user,
|
|
1245
|
+
aliases: input.alias,
|
|
1246
|
+
environment: input.environment,
|
|
1247
|
+
from: input.from,
|
|
1248
|
+
to: input.to,
|
|
1249
|
+
context: input.context
|
|
1250
|
+
};
|
|
1251
|
+
const named = input.context === void 0 ? void 0 : parseContextJson(input.context).organizationId;
|
|
1252
|
+
const scope = input.app === void 0 ? { organizationId: input.org ?? (named === void 0 ? await resolveOrganization(ctx, void 0) : String(named)) } : await resolveAppScope(ctx.api, input.app, input.org);
|
|
1253
|
+
const { organizationId } = scope;
|
|
1254
|
+
if (organizationId === void 0) throw new WorkspaceError(`Couldn't find the organization of app ${input.app}. Say which with --org <id>.`);
|
|
1255
|
+
if (!/^[1-9]\d*$/.test(organizationId)) throw new WorkspaceError(`--org takes an organization's id, a number. Got ${organizationId}.`);
|
|
1256
|
+
return {
|
|
1257
|
+
...context,
|
|
1258
|
+
...scope,
|
|
1259
|
+
organizationId
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
async function runWorkspaceDev(ctx, input, seams = {}) {
|
|
1263
|
+
const { root } = readProject(input.dir);
|
|
1264
|
+
ctx.ui.intro("Workspace dev");
|
|
1265
|
+
warnIfSdkBehind(ctx.ui, root);
|
|
1266
|
+
const defaults = await resolveDefaults(ctx, input);
|
|
1267
|
+
const { credential, limitedTo } = agentCredential(ctx, defaults.organizationId);
|
|
1268
|
+
await credential.current();
|
|
1269
|
+
const first = await bundleWorkspace(root, seams.wrangler);
|
|
1270
|
+
const log = {
|
|
1271
|
+
info: (text) => ctx.ui.step(text),
|
|
1272
|
+
warn: (text) => ctx.ui.warn(text)
|
|
1273
|
+
};
|
|
1274
|
+
let manifest = readManifest(root);
|
|
1275
|
+
const runtime = await (seams.startRuntime ?? startMiniflare)({
|
|
1276
|
+
root,
|
|
1277
|
+
module: first.module,
|
|
1278
|
+
compatibility: first.compatibility,
|
|
1279
|
+
outbound: createOutbound({
|
|
1280
|
+
apiOrigin: ctx.api.host,
|
|
1281
|
+
credential,
|
|
1282
|
+
log,
|
|
1283
|
+
declaredScopes: () => manifest.scopes,
|
|
1284
|
+
limitedTo,
|
|
1285
|
+
...seams.fetchImpl ? { fetchImpl: seams.fetchImpl } : {}
|
|
1286
|
+
})
|
|
1287
|
+
});
|
|
1288
|
+
let server;
|
|
1289
|
+
let unwatch;
|
|
1290
|
+
let rebuilding = Promise.resolve();
|
|
1291
|
+
let stopping;
|
|
1292
|
+
const stop = () => {
|
|
1293
|
+
stopping ??= (async () => {
|
|
1294
|
+
unwatch?.();
|
|
1295
|
+
await rebuilding;
|
|
1296
|
+
await server?.close();
|
|
1297
|
+
await runtime.dispose();
|
|
1298
|
+
})();
|
|
1299
|
+
return stopping;
|
|
1300
|
+
};
|
|
1301
|
+
const offCancel = ctx.onCancel?.(stop);
|
|
1302
|
+
try {
|
|
1303
|
+
const started = await startDevServer({
|
|
1304
|
+
getManifest: () => manifest,
|
|
1305
|
+
runtime,
|
|
1306
|
+
port: input.port,
|
|
1307
|
+
defaults
|
|
1308
|
+
});
|
|
1309
|
+
server = started;
|
|
1310
|
+
const rebuild = () => {
|
|
1311
|
+
rebuilding = rebuilding.then(async () => {
|
|
1312
|
+
try {
|
|
1313
|
+
const nextManifest = readManifest(root);
|
|
1314
|
+
const next = await bundleWorkspace(root, seams.wrangler);
|
|
1315
|
+
await runtime.update(next.module, next.compatibility);
|
|
1316
|
+
manifest = nextManifest;
|
|
1317
|
+
ctx.ui.step(`Rebuilt, ${next.bytes} bytes`);
|
|
1318
|
+
started.publish({ type: "reload" });
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
ctx.ui.error(error.message);
|
|
1321
|
+
started.publish({
|
|
1322
|
+
type: "error",
|
|
1323
|
+
message: error.message
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
});
|
|
1327
|
+
return rebuilding;
|
|
1328
|
+
};
|
|
1329
|
+
unwatch = watchProject(root, () => void rebuild());
|
|
1330
|
+
ctx.ui.success(`Open ${started.hostOrigin}`);
|
|
1331
|
+
const reach = limitedTo() === void 0 ? "" : `, limited to organization ${defaults.organizationId}`;
|
|
1332
|
+
ctx.ui.info(`API calls use a read-only token as you${reach}. Writes, outside hosts and raw sockets are refused.`);
|
|
1333
|
+
seams.onReady?.({
|
|
1334
|
+
host: started.hostOrigin,
|
|
1335
|
+
frame: started.frameOrigin
|
|
1336
|
+
}, rebuild);
|
|
1337
|
+
await (seams.until ?? waitForSignal)(stop);
|
|
1338
|
+
} finally {
|
|
1339
|
+
offCancel?.();
|
|
1340
|
+
await stop();
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
//#endregion
|
|
1345
|
+
export { runWorkspaceDev, watchProject };
|