@uniformdev/canvas-next 19.8.0 → 19.9.2-alpha.3

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.
@@ -30,176 +30,379 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/route/index.ts
31
31
  var route_exports = {};
32
32
  __export(route_exports, {
33
+ getStaticPaths: () => getStaticPaths2,
33
34
  unstable_getServerSideProps: () => unstable_getServerSideProps,
34
- unstable_logIssues: () => unstable_logIssues,
35
- unstable_withUniformGetServerSideProps: () => unstable_withUniformGetServerSideProps
35
+ unstable_getStaticProps: () => unstable_getStaticProps,
36
+ unstable_withUniformGetServerSideProps: () => unstable_withUniformGetServerSideProps,
37
+ unstable_withUniformGetStaticProps: () => unstable_withUniformGetStaticProps,
38
+ withUniformGetStaticPaths: () => withUniformGetStaticPaths
36
39
  });
37
40
  module.exports = __toCommonJS(route_exports);
38
41
 
39
- // src/route/withUniformGetServerSideProps.ts
42
+ // src/project-map/withUniformGetServerSideProps.ts
40
43
  var import_canvas = require("@uniformdev/canvas");
41
- var import_chalk3 = __toESM(require("chalk"));
44
+ var withUniformGetServerSideProps = (options) => {
45
+ const canvasClient = (options == null ? void 0 : options.client) || new import_canvas.CanvasClient({
46
+ apiKey: process.env.UNIFORM_API_KEY,
47
+ projectId: process.env.UNIFORM_PROJECT_ID,
48
+ apiHost: process.env.UNIFORM_CLI_BASE_URL,
49
+ edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
50
+ });
51
+ return async function wrappedGetServerSideProps(context) {
52
+ var _a, _b;
53
+ const projectMapId = (_a = options == null ? void 0 : options.projectMapId) != null ? _a : process.env.UNIFORM_PROJECT_MAP_ID;
54
+ const { preview, previewData } = context;
55
+ let composition = void 0;
56
+ let nodePath = (options == null ? void 0 : options.prefix) ? context.resolvedUrl.replace(new RegExp(`^${options.prefix}`), "") : context.resolvedUrl;
57
+ if (options == null ? void 0 : options.modifyPath) {
58
+ nodePath = options.modifyPath(nodePath, context);
59
+ }
60
+ if (previewData == null ? void 0 : previewData.isUniformContextualEditing) {
61
+ composition = { ...import_canvas.EMPTY_COMPOSITION, _id: (_b = previewData.compositionId) != null ? _b : import_canvas.EMPTY_COMPOSITION._id };
62
+ } else {
63
+ try {
64
+ const time = Date.now();
65
+ const response = await canvasClient.getCompositionByNodePath({
66
+ ...options == null ? void 0 : options.requestOptions,
67
+ projectMapId,
68
+ projectMapNodePath: nodePath,
69
+ state: preview || (options == null ? void 0 : options.preview) ? import_canvas.CANVAS_DRAFT_STATE : import_canvas.CANVAS_PUBLISHED_STATE
70
+ });
71
+ const duration = Date.now() - time;
72
+ composition = response.composition;
73
+ if (!(options == null ? void 0 : options.silent)) {
74
+ (0, import_canvas.logCompositionResponse)(response, duration);
75
+ }
76
+ } catch (e) {
77
+ console.error("[canvas-next] Failed to fetch composition", e);
78
+ return {
79
+ notFound: true
80
+ };
81
+ }
82
+ }
83
+ const ret = (options == null ? void 0 : options.callback) ? await options.callback(context, composition) : { props: {} };
84
+ if (Object.hasOwn(ret, "props")) {
85
+ const casted = ret;
86
+ casted.props["data"] = composition;
87
+ }
88
+ return ret;
89
+ };
90
+ };
42
91
 
43
- // src/route/defaultHandleComposition.ts
44
- var import_chalk2 = __toESM(require("chalk"));
92
+ // src/project-map/withUniformGetStaticPaths.ts
93
+ var import_canvas2 = require("@uniformdev/canvas");
94
+ var import_project_map = require("@uniformdev/project-map");
95
+ var withUniformGetStaticPaths = (options) => {
96
+ return async function wrappedGetStaticPaths() {
97
+ var _a, _b;
98
+ const projectMapId = (_a = options == null ? void 0 : options.projectMapId) != null ? _a : process.env.UNIFORM_PROJECT_MAP_ID;
99
+ const projectMapClient = (_b = options == null ? void 0 : options.client) != null ? _b : new import_project_map.ProjectMapClient({
100
+ apiKey: process.env.UNIFORM_API_KEY,
101
+ projectId: process.env.UNIFORM_PROJECT_ID,
102
+ apiHost: process.env.UNIFORM_CLI_BASE_URL
103
+ });
104
+ const response = await projectMapClient.getNodes({
105
+ ...options == null ? void 0 : options.requestOptions,
106
+ path: options == null ? void 0 : options.rootPath,
107
+ projectMapId,
108
+ state: (options == null ? void 0 : options.preview) ? import_canvas2.CANVAS_DRAFT_STATE : import_canvas2.CANVAS_PUBLISHED_STATE
109
+ });
110
+ const nodes = (options == null ? void 0 : options.callback) ? await options.callback(response.nodes) : response.nodes;
111
+ const paths = nodes == null ? void 0 : nodes.filter((node) => Boolean(node.compositionId)).map((node) => {
112
+ var _a2;
113
+ return `${(_a2 = options == null ? void 0 : options.prefix) != null ? _a2 : ""}${node.path}`;
114
+ });
115
+ return {
116
+ paths,
117
+ fallback: true
118
+ };
119
+ };
120
+ };
45
121
 
46
- // src/route/logIssues.ts
47
- var import_chalk = __toESM(require("chalk"));
48
- function unstable_logIssues(prefix, issues, colour) {
49
- colour = colour != null ? colour : "red";
50
- const reversedIssues = [...issues].reverse();
51
- console.error(
52
- `${import_chalk.default[colour](prefix)}
53
- ${reversedIssues.map(
54
- (issue) => `${import_chalk.default[colour](">")} ${import_chalk.default.italic.gray(indent(issue.type.toUpperCase(), 7))} ${renderIssue(
55
- issue
56
- )}`
57
- ).join("\n")}`
58
- );
59
- }
60
- function renderIssue(issue) {
61
- var _a;
62
- let path;
63
- let type;
64
- let message = issue.message;
65
- let detail;
66
- if (issue.type !== "config") {
67
- path = issue.componentPath;
68
- type = issue.componentType;
69
- message = issue.message;
70
- }
71
- if (issue.type === "binding") {
72
- detail = `Binding expression: ${(_a = issue.expression) == null ? void 0 : _a.pointer}`;
73
- } else if (issue.type === "data") {
74
- detail = `Data resource name: ${issue.dataName}, data type: ${issue.dataType}`;
75
- }
76
- if (issue.type === "input") {
77
- detail = issue.inputName;
78
- }
79
- let result = `${import_chalk.default.white(blockify(message))}`;
80
- if (detail) {
81
- result += `
82
- ${indent(" ", 10)}${import_chalk.default.gray(`${detail}`)}`;
83
- }
84
- if (path && type) {
85
- result += `
86
- ${indent(" ", 10)}${import_chalk.default.gray(`Occurred on component ${type} at slot path ${path}`)}`;
87
- }
88
- return result;
89
- }
90
- function indent(str, len) {
91
- const indent2 = len != null ? len : 10;
92
- return str.padStart(indent2);
93
- }
94
- function blockify(str, len) {
95
- const indentSize = len != null ? len : 10;
96
- return str.split("\n").map((line, index) => index === 0 ? line : `${indent(" ", indentSize)}${line}`).join("\n");
97
- }
122
+ // src/project-map/withUniformGetStaticProps.ts
123
+ var import_canvas3 = require("@uniformdev/canvas");
98
124
 
99
- // src/route/defaultHandleComposition.ts
100
- function defaultHandleComposition(matched) {
101
- var _a, _b;
102
- const resErrors = (_a = matched.compositionApiResponse.errors) != null ? _a : [];
103
- const resWarnings = (_b = matched.compositionApiResponse.warnings) != null ? _b : [];
104
- const colour = resErrors.length > 0 ? "red" : resWarnings.length > 0 ? "yellow" : "green";
105
- console.log(`[canvas-next] ${import_chalk2.default[colour]("matched")} ${matched.matchedRoute}`, matched.type);
106
- if (matched.dynamicInputs) {
107
- const entries = Object.entries(matched.dynamicInputs);
108
- if (entries.length > 0) {
109
- console.log(
110
- ` ${import_chalk2.default.gray("Matched dynamic inputs:\n ")}`,
111
- entries.map(([k, v]) => `${k}: ${v}`).join("\n ")
112
- );
113
- }
114
- }
115
- if (resErrors.length > 0) {
116
- unstable_logIssues(
117
- `[canvas-next] ${matched.matchedRoute} composition data error${resErrors.length === 1 ? "" : "s"}; some content may be missing`,
118
- resErrors,
119
- "red"
120
- );
121
- }
122
- if (resWarnings.length > 0) {
123
- unstable_logIssues(
124
- `[canvas-next] ${matched.matchedRoute} composition data warning${resWarnings.length === 1 ? "" : "s"}; some content may be missing`,
125
- resWarnings,
126
- "yellow"
127
- );
128
- }
129
- if (matched.compositionApiResponse.diagnostics) {
130
- console.log(`[canvas-next] ${import_chalk2.default.green("Route diagnostics are enabled. Diagnostic data:")}`);
131
- console.log(JSON.stringify(matched.compositionApiResponse.diagnostics, null, 2));
132
- }
133
- return matched.compositionApiResponse.composition;
134
- }
125
+ // src/helpers/resolveSlugFromParams.ts
126
+ var resolveSlugFromParams = ({
127
+ param = "slug",
128
+ params
129
+ }) => {
130
+ const slug = (params == null ? void 0 : params[param]) || "";
131
+ const slugString = Array.isArray(slug) ? slug.join("/") : slug;
132
+ return `/${slugString}`;
133
+ };
135
134
 
136
- // src/route/withUniformGetServerSideProps.ts
137
- var unstable_withUniformGetServerSideProps = (options) => {
138
- var _a, _b, _c, _d;
139
- const handleRedirect = (_a = options == null ? void 0 : options.handleRedirect) != null ? _a : () => {
140
- throw new Error(`Redirects are not yet implemented by default. Please override handleRedirect option.`);
141
- };
142
- const handleNotFound = (_b = options == null ? void 0 : options.handleNotFound) != null ? _b : () => ({ notFound: true });
143
- const handleComposition = (_c = options == null ? void 0 : options.handleComposition) != null ? _c : defaultHandleComposition;
144
- const handleModifyPath = (_d = options == null ? void 0 : options.modifyPath) != null ? _d : (path) => decodeURI(path);
145
- return async function wrappedGetServerSideProps(context) {
146
- var _a2, _b2;
135
+ // src/project-map/withUniformGetStaticProps.ts
136
+ var withUniformGetStaticProps = (options) => {
137
+ var _a;
138
+ const canvasClient = (_a = options == null ? void 0 : options.client) != null ? _a : new import_canvas3.CanvasClient({
139
+ apiKey: process.env.UNIFORM_API_KEY,
140
+ projectId: process.env.UNIFORM_PROJECT_ID,
141
+ apiHost: process.env.UNIFORM_CLI_BASE_URL,
142
+ edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
143
+ });
144
+ return async function wrappedGetStaticProps(context) {
145
+ var _a2, _b;
147
146
  const projectMapId = (_a2 = options == null ? void 0 : options.projectMapId) != null ? _a2 : process.env.UNIFORM_PROJECT_MAP_ID;
148
- const routeClient = (options == null ? void 0 : options.client) || new import_canvas.unstable_RouteClient({
149
- apiKey: process.env.UNIFORM_API_KEY,
150
- projectId: process.env.UNIFORM_PROJECT_ID,
151
- edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
147
+ let pathString = resolveSlugFromParams({
148
+ param: options == null ? void 0 : options.param,
149
+ params: context == null ? void 0 : context.params
152
150
  });
153
- const { previewData } = context;
151
+ if (options == null ? void 0 : options.modifyPath) {
152
+ pathString = options.modifyPath(pathString, context);
153
+ }
154
+ const { preview, previewData } = context;
154
155
  let composition = void 0;
155
- let nodePath = (options == null ? void 0 : options.prefix) ? context.resolvedUrl.replace(new RegExp(`^${options.prefix}`), "") : context.resolvedUrl;
156
- nodePath = handleModifyPath(nodePath, context);
157
156
  if (previewData == null ? void 0 : previewData.isUniformContextualEditing) {
158
- composition = { ...import_canvas.EMPTY_COMPOSITION, _id: (_b2 = previewData.compositionId) != null ? _b2 : import_canvas.EMPTY_COMPOSITION._id };
157
+ composition = { ...import_canvas3.EMPTY_COMPOSITION, _id: (_b = previewData.compositionId) != null ? _b : import_canvas3.EMPTY_COMPOSITION._id };
159
158
  } else {
160
159
  try {
161
- console.log("[canvas-next] get route", nodePath);
162
- const response = await routeClient.getRoute({
160
+ const time = Date.now();
161
+ const response = await canvasClient.getCompositionByNodePath({
163
162
  ...options == null ? void 0 : options.requestOptions,
164
163
  projectMapId,
164
+ projectMapNodePath: pathString,
165
+ state: preview || (options == null ? void 0 : options.preview) ? import_canvas3.CANVAS_DRAFT_STATE : import_canvas3.CANVAS_PUBLISHED_STATE
166
+ });
167
+ const duration = Date.now() - time;
168
+ composition = response.composition;
169
+ if (!(options == null ? void 0 : options.silent)) {
170
+ (0, import_canvas3.logCompositionResponse)(response, duration);
171
+ }
172
+ } catch (e) {
173
+ console.error("[canvas-next] Failed to fetch composition", e);
174
+ return {
175
+ notFound: true
176
+ };
177
+ }
178
+ }
179
+ const ret = options.callback ? await options.callback(context, composition) : { props: {} };
180
+ if (composition && Object.hasOwn(ret, "props")) {
181
+ const casted = ret;
182
+ casted.props["data"] = composition;
183
+ }
184
+ return ret;
185
+ };
186
+ };
187
+
188
+ // src/project-map/index.ts
189
+ var getServerSideProps = withUniformGetServerSideProps();
190
+ var getStaticProps = withUniformGetStaticProps({ param: "path" });
191
+ var getStaticPaths = withUniformGetStaticPaths();
192
+
193
+ // src/route/withUniformGetServerSideProps.ts
194
+ var import_redirect = require("@uniformdev/redirect");
195
+
196
+ // src/route/createRouteFetcher.ts
197
+ var import_canvas4 = require("@uniformdev/canvas");
198
+ var import_ansi_colors = __toESM(require("ansi-colors"));
199
+ var { red } = import_ansi_colors.default;
200
+ function createRouteFetcher(options) {
201
+ const {
202
+ handleNotFound,
203
+ handleComposition,
204
+ handleRedirect,
205
+ defaultHandleComposition,
206
+ defaultHandleNotFound,
207
+ defaultHandleRedirect,
208
+ modifyPath,
209
+ projectMapId = process.env.UNIFORM_PROJECT_MAP_ID,
210
+ client,
211
+ prefix,
212
+ requestOptions,
213
+ silent,
214
+ parseContext
215
+ } = options;
216
+ const routeClient = client || new import_canvas4.unstable_RouteClient({
217
+ apiKey: process.env.UNIFORM_API_KEY,
218
+ projectId: process.env.UNIFORM_PROJECT_ID,
219
+ edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
220
+ });
221
+ const handleModifyPath = modifyPath != null ? modifyPath : (path) => decodeURI(path);
222
+ return async function fetcher(context) {
223
+ const { contextualEditingCompositionId, resolvedUrl } = parseContext(context);
224
+ let nodePath = prefix ? resolvedUrl.replace(new RegExp(`^${prefix}`), "") : resolvedUrl;
225
+ nodePath = handleModifyPath(nodePath, context);
226
+ const invokeRedirectResult = (redirect, duration) => (handleRedirect != null ? handleRedirect : defaultHandleRedirect)(
227
+ nodePath,
228
+ redirect,
229
+ context,
230
+ (response) => defaultHandleRedirect(
231
+ nodePath,
232
+ response,
233
+ context,
234
+ () => {
235
+ throw new Error();
236
+ },
237
+ duration
238
+ ),
239
+ duration
240
+ );
241
+ const invokeNotFoundResult = (response, duration) => (handleNotFound != null ? handleNotFound : defaultHandleNotFound)(
242
+ response,
243
+ context,
244
+ (response2) => defaultHandleNotFound(
245
+ response2,
246
+ context,
247
+ () => {
248
+ throw new Error();
249
+ },
250
+ duration
251
+ ),
252
+ duration
253
+ );
254
+ const invokeCompositionResult = (response, duration) => (handleComposition != null ? handleComposition : defaultHandleComposition)(
255
+ response,
256
+ context,
257
+ (response2) => defaultHandleComposition(
258
+ response2,
259
+ context,
260
+ () => {
261
+ throw new Error();
262
+ },
263
+ duration
264
+ ),
265
+ duration
266
+ );
267
+ if (contextualEditingCompositionId) {
268
+ const previewEmptyComposition = await invokeCompositionResult(
269
+ {
270
+ type: "composition",
271
+ matchedRoute: "contextual-editing",
272
+ compositionApiResponse: {
273
+ composition: {
274
+ ...import_canvas4.EMPTY_COMPOSITION,
275
+ _id: contextualEditingCompositionId != null ? contextualEditingCompositionId : import_canvas4.EMPTY_COMPOSITION._id
276
+ }
277
+ }
278
+ },
279
+ 0
280
+ );
281
+ return previewEmptyComposition;
282
+ } else {
283
+ try {
284
+ console.log("Fetch route", nodePath);
285
+ const time = Date.now();
286
+ const response = await routeClient.getRoute({
287
+ ...requestOptions,
288
+ projectMapId,
165
289
  path: nodePath
166
290
  });
291
+ const duration = Date.now() - time;
292
+ if (!silent) {
293
+ (0, import_canvas4.logRouteResponse)(response, duration);
294
+ }
167
295
  if (response.type === "redirect") {
168
- return handleRedirect(response, context);
296
+ return invokeRedirectResult(response, duration);
169
297
  }
170
298
  if (response.type === "notFound") {
171
- return handleNotFound(response, context);
299
+ return invokeNotFoundResult(response, duration);
172
300
  }
173
- const handleResult = handleComposition(response, context, defaultHandleComposition);
301
+ const handleResult = await invokeCompositionResult(response, duration);
174
302
  if (!handleResult) {
175
- return { notFound: true };
303
+ return invokeNotFoundResult({ type: "notFound" }, duration);
176
304
  }
177
- composition = handleResult;
305
+ return handleResult;
178
306
  } catch (e) {
179
- console.error(import_chalk3.default.red("[canvas-next] Failed to fetch composition"), e);
180
- if (e instanceof import_canvas.ApiClientError) {
307
+ console.error(red("Failed to fetch route"), e);
308
+ if (e instanceof import_canvas4.ApiClientError) {
181
309
  if (e.statusCode === 404) {
182
- return { notFound: true };
310
+ return invokeNotFoundResult({ type: "notFound" }, 0);
183
311
  }
184
- throw new Error(`Failed to fetch composition. See server logs for details.`);
312
+ throw new Error(`Failed to fetch route. See server logs for details.`);
185
313
  }
186
314
  throw e;
187
315
  }
188
316
  }
189
- const ret = (options == null ? void 0 : options.callback) ? await options.callback(context, composition) : { props: {} };
190
- if (Object.hasOwn(ret, "props")) {
191
- const casted = ret;
192
- casted.props["data"] = composition;
317
+ };
318
+ }
319
+
320
+ // src/route/withUniformGetServerSideProps.ts
321
+ var unstable_withUniformGetServerSideProps = (options) => {
322
+ const defaultHandleRedirect = (requestUrl, matched) => {
323
+ return {
324
+ redirect: {
325
+ destination: import_redirect.RedirectClient.getTargetVariableExpandedUrl(requestUrl, matched.redirect),
326
+ statusCode: matched.redirect.targetStatusCode
327
+ }
328
+ };
329
+ };
330
+ const defaultHandleNotFound = () => ({
331
+ notFound: true
332
+ });
333
+ const defaultHandleComposition = async (matched) => {
334
+ return {
335
+ props: {
336
+ data: matched.compositionApiResponse.composition
337
+ }
338
+ };
339
+ };
340
+ const routeFetcher = createRouteFetcher({
341
+ ...options,
342
+ defaultHandleComposition,
343
+ defaultHandleNotFound,
344
+ defaultHandleRedirect,
345
+ parseContext(context) {
346
+ var _a;
347
+ return {
348
+ contextualEditingCompositionId: (_a = context.previewData) == null ? void 0 : _a.compositionId,
349
+ resolvedUrl: context.resolvedUrl
350
+ };
193
351
  }
194
- return ret;
352
+ });
353
+ return routeFetcher;
354
+ };
355
+
356
+ // src/route/withUniformGetStaticProps.ts
357
+ var import_redirect2 = require("@uniformdev/redirect");
358
+ var unstable_withUniformGetStaticProps = (options) => {
359
+ const defaultHandleRedirect = (requestUrl, matched) => {
360
+ return {
361
+ redirect: {
362
+ destination: import_redirect2.RedirectClient.getTargetVariableExpandedUrl(requestUrl, matched.redirect),
363
+ statusCode: matched.redirect.targetStatusCode
364
+ }
365
+ };
195
366
  };
367
+ const defaultHandleNotFound = () => ({
368
+ notFound: true
369
+ });
370
+ const defaultHandleComposition = async (matched) => {
371
+ return {
372
+ props: {
373
+ data: matched.compositionApiResponse.composition
374
+ }
375
+ };
376
+ };
377
+ const routeFetcher = createRouteFetcher({
378
+ ...options,
379
+ defaultHandleComposition,
380
+ defaultHandleNotFound,
381
+ defaultHandleRedirect,
382
+ parseContext(context) {
383
+ var _a, _b;
384
+ return {
385
+ contextualEditingCompositionId: (_a = context.previewData) == null ? void 0 : _a.compositionId,
386
+ resolvedUrl: resolveSlugFromParams({
387
+ params: context.params,
388
+ param: (_b = options == null ? void 0 : options.param) != null ? _b : "route"
389
+ })
390
+ };
391
+ }
392
+ });
393
+ return routeFetcher;
196
394
  };
197
395
 
198
396
  // src/route/index.ts
199
397
  var unstable_getServerSideProps = unstable_withUniformGetServerSideProps();
398
+ var unstable_getStaticProps = unstable_withUniformGetStaticProps();
399
+ var getStaticPaths2 = withUniformGetStaticPaths();
200
400
  // Annotate the CommonJS export names for ESM import in node:
201
401
  0 && (module.exports = {
402
+ getStaticPaths,
202
403
  unstable_getServerSideProps,
203
- unstable_logIssues,
204
- unstable_withUniformGetServerSideProps
404
+ unstable_getStaticProps,
405
+ unstable_withUniformGetServerSideProps,
406
+ unstable_withUniformGetStaticProps,
407
+ withUniformGetStaticPaths
205
408
  });