@pantheon-systems/p1-next-sdk 0.23.0 → 0.25.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.
Files changed (54) hide show
  1. package/README.md +99 -1
  2. package/bin/lib/cli.js +143 -25
  3. package/bin/lib/detect.js +14 -2
  4. package/bin/lib/fs-ops.js +2 -1
  5. package/bin/lib/localized-pages.js +522 -0
  6. package/bin/lib/messages.js +38 -23
  7. package/bin/templates/localized-pages/app/[[...puckPath]]/layout.tsx.template +29 -0
  8. package/bin/templates/localized-pages/app/[[...puckPath]]/page.tsx.template +24 -0
  9. package/bin/templates/localized-pages/app/p1/layout.tsx.template +11 -0
  10. package/bin/templates/localized-pages/components/html-shell.tsx.template +28 -0
  11. package/bin/templates/localized-pages/components/locale-suggestion.module.css.template +74 -0
  12. package/bin/templates/localized-pages/components/locale-suggestion.tsx.template +94 -0
  13. package/bin/templates/localized-pages/legacy/app/[...puckPath]/page.tsx.template +23 -0
  14. package/bin/templates/localized-pages/legacy/app/layout.tsx.template +37 -0
  15. package/bin/templates/localized-pages/legacy/app/layout.v1.tsx.template +27 -0
  16. package/bin/templates/localized-pages/legacy/app/page.tsx.template +19 -0
  17. package/bin/templates/localized-pages/lib/locale-name.ts.template +9 -0
  18. package/dist/chatbot/chatbot-plugin.js +3 -0
  19. package/dist/create-published-page.d.ts +22 -9
  20. package/dist/create-published-page.js +59 -8
  21. package/dist/editor-client/editor-content.js +3 -0
  22. package/dist/editor-client/use-business-account-id.d.ts +5 -0
  23. package/dist/editor-client/use-business-account-id.js +7 -0
  24. package/dist/experimental-features/features.d.ts +16 -5
  25. package/dist/experimental-features/features.js +6 -5
  26. package/dist/experimental-features/resolve-features.d.ts +5 -2
  27. package/dist/experimental-features/resolve-features.js +7 -4
  28. package/dist/experimental-features/session-cache.d.ts +1 -1
  29. package/dist/experimental-features/session-cache.js +2 -2
  30. package/dist/experimental-features/use-p1-experimental-features.d.ts +10 -3
  31. package/dist/experimental-features/use-p1-experimental-features.js +29 -11
  32. package/dist/handler.d.ts +2 -1
  33. package/dist/index.d.ts +1 -0
  34. package/dist/index.js +1 -0
  35. package/dist/localization/index.d.ts +4 -0
  36. package/dist/localization/index.js +3 -0
  37. package/dist/localization/saved-locale.d.ts +13 -0
  38. package/dist/localization/saved-locale.js +20 -0
  39. package/dist/localization-react.d.ts +40 -0
  40. package/dist/localization-react.js +15 -0
  41. package/dist/page-localization.d.ts +12 -0
  42. package/dist/page-localization.js +9 -0
  43. package/dist/pages-handler.js +2 -2
  44. package/dist/routes/publish.d.ts +0 -2
  45. package/dist/routes/publish.js +2 -3
  46. package/dist/routes/revalidate.d.ts +4 -4
  47. package/dist/routes/revalidate.js +10 -4
  48. package/dist/server.d.ts +2 -0
  49. package/dist/server.js +1 -0
  50. package/docs/migrations/editor-layout.md +213 -0
  51. package/docs/migrations/localized-pages.md +208 -0
  52. package/package.json +9 -3
  53. package/dist/chatbot/flag-context.d.ts +0 -15
  54. package/dist/chatbot/flag-context.js +0 -13
@@ -0,0 +1,522 @@
1
+ /**
2
+ * The localized-pages migration: serve the home page and every published page
3
+ * from one optional catch-all, `app/[[...puckPath]]`, under a root layout that
4
+ * sets `<html lang>` from the page shown. The editor gets a root layout of its
5
+ * own at `app/p1/layout.tsx`, and both render through `components/html-shell.tsx`.
6
+ * The locale-prompt migration then adds the saved-language prompt to that
7
+ * route's page client.
8
+ *
9
+ * Every file a migration writes or deletes is validated first: the root layout,
10
+ * home page, catch-all page and old-layout tests it replaces or removes must
11
+ * match a scaffolded version, a file it edits must have the shape the edit
12
+ * expects, and a file it carries from the scaffold is written only where none
13
+ * exists. Anything else makes it bail with the tree untouched.
14
+ */
15
+
16
+ import { createHash } from "node:crypto";
17
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
18
+ import { dirname, join, relative, sep } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { isRouteSpecial } from "./detect.js";
21
+ import { BailError } from "./transform.js";
22
+
23
+ const TEMPLATES = join(dirname(fileURLToPath(import.meta.url)), "..", "templates", "localized-pages");
24
+
25
+ /** A scaffolded file: the current starter's, or an earlier one's under `legacy/`. */
26
+ export function template(rel) {
27
+ return readFileSync(join(TEMPLATES, `${rel}.template`), "utf-8");
28
+ }
29
+
30
+ const OLD_SEGMENT = "[...puckPath]";
31
+ const NEW_SEGMENT = "[[...puckPath]]";
32
+ const GUIDE = "node_modules/@pantheon-systems/p1-next-sdk/docs/migrations/localized-pages.md";
33
+ const COMMAND = "npx @pantheon-systems/p1-next-sdk migrate";
34
+
35
+ const normalize = (source) => source.replace(/\r\n/g, "\n").replace(/[ \t]+$/gm, "").trimEnd();
36
+ const sameSource = (a, b) => normalize(a) === normalize(b);
37
+ const sourceHash = (source) => createHash("sha256").update(normalize(source)).digest("hex");
38
+
39
+ /** Run a text edit on LF line endings, keeping the source's own endings in the result. */
40
+ function editLf(source, edit) {
41
+ const crlf = source.includes("\r\n");
42
+ const out = edit(source.replace(/\r\n/g, "\n"));
43
+ return crlf ? out.replace(/\n/g, "\r\n") : out;
44
+ }
45
+
46
+ const LEGACY_LAYOUTS = ["legacy/app/layout.tsx", "legacy/app/layout.v1.tsx"];
47
+
48
+ /**
49
+ * Tests earlier starters scaffolded and current ones do not, each with the
50
+ * `sourceHash` of every scaffolded version.
51
+ */
52
+ export const LEGACY_TESTS = {
53
+ "published-page-routes.test.ts": [
54
+ "c2e42d6dfdf8f4f0f95e0b54d6a811cdc174316835c849f4d764776418e675e9",
55
+ "46a78dbca5bb385c1a00e1779ae5a1449500dcdd9065a15fa1ce0984f5bba7dc",
56
+ ],
57
+ "widget-logout.test.ts": ["be236727e20d255bfde2e947cc1d61397848526bcd3f4ede38eadb52526e0cf3"],
58
+ "styles-canvas-scope.test.ts": ["6d612c7cb5f98ff7ffb61cb762da71bc30f8535f4d9f058e5771fe44da1ebae0"],
59
+ "editor-route-group.test.ts": [
60
+ "74d87745768a3fec9bca2af178ae5dafcb2943ffa20bd93f5bfc8eacf46cddce",
61
+ "330118a940365fb852cd775c8ccbf88a011b21148b282b203bd291b90c91e337",
62
+ ],
63
+ };
64
+
65
+ /**
66
+ * Moving a file from `app/` into `app/[[...puckPath]]/` puts it one directory
67
+ * deeper, so sibling imports become parent imports and parent imports gain
68
+ * one more `../`.
69
+ */
70
+ export function moveImportsOneLevelDeeper(source) {
71
+ return source.replace(
72
+ /(\bfrom\s+|\bimport\s+|\bimport\(\s*|\brequire\(\s*)(['"])(\.\.?\/)/g,
73
+ (_match, prefix, quote, dots) => `${prefix}${quote}${dots === "./" ? "../" : "../../"}`,
74
+ );
75
+ }
76
+
77
+ const PUBLISHED_PAGES_HEADER_OLD = `/**
78
+ * The app's published-page routes, built once and shared by both route files.
79
+ *
80
+ * One instance on purpose: the factory memoizes per-request work (the CCR query
81
+ * fetchers), and "/" and the catch-all should share that rather than each
82
+ * building their own.
83
+ */`;
84
+
85
+ const PUBLISHED_PAGES_HEADER_NEW = `/**
86
+ * The app's published-page route, built once and shared by the route and its
87
+ * layout.
88
+ *
89
+ * One instance on purpose: the factory memoizes per-request work (the CCR query
90
+ * fetchers), and the route and its layout should share that rather than each
91
+ * building their own.
92
+ */`;
93
+
94
+ /** Point `app/published-pages.tsx` at the client's new directory. */
95
+ export function rewritePublishedPages(original) {
96
+ return editLf(original, (source) => {
97
+ const oldImport = `"./${OLD_SEGMENT}/client"`;
98
+ const newImport = `"./${NEW_SEGMENT}/client"`;
99
+ if (!source.includes(oldImport)) {
100
+ throw new BailError(
101
+ `app/published-pages.tsx does not import its Client from ${oldImport}; ` +
102
+ `update that import to ${newImport} by hand. See ${GUIDE}.`,
103
+ );
104
+ }
105
+ return source.replace(oldImport, newImport).replace(PUBLISHED_PAGES_HEADER_OLD, PUBLISHED_PAGES_HEADER_NEW);
106
+ });
107
+ }
108
+
109
+ /**
110
+ * Hand the page's localization to the saved-language prompt. Every anchor has
111
+ * to match: a client already rendering the prompt is left alone, and one that
112
+ * changed part of this region is migrated by hand.
113
+ */
114
+ const PROMPT_EDITS = [
115
+ [
116
+ `import config from "../../puck.config";\n`,
117
+ `import type { PublishedPageLocalization } from "@pantheon-systems/p1-next-sdk";\n` +
118
+ `import config from "../../puck.config";\n` +
119
+ `import { LocaleSuggestion } from "../../components/locale-suggestion";\n`,
120
+ ],
121
+ [
122
+ `export function Client({\n data,\n pageMetadata,\n}: {\n`,
123
+ `export function Client({\n data,\n pageMetadata,\n localization,\n}: {\n`,
124
+ ],
125
+ [
126
+ ` pageType?: "page" | "template" | "override";\n };\n}) {\n`,
127
+ ` pageType?: "page" | "template" | "override";\n };\n localization?: PublishedPageLocalization;\n}) {\n`,
128
+ ],
129
+ [
130
+ ` <RenderClient config={config} data={data} />\n`,
131
+ ` <RenderClient config={config} data={data} />\n {localization && <LocaleSuggestion />}\n`,
132
+ ],
133
+ ];
134
+
135
+ export function addLocalePrompt(original) {
136
+ return editLf(original, (source) => {
137
+ if (source.includes("<LocaleSuggestion")) return source;
138
+ const missing = PROMPT_EDITS.filter(([find]) => !source.includes(find));
139
+ if (missing.length > 0) {
140
+ throw new BailError(
141
+ `The page client (${NEW_SEGMENT}/client.tsx) differs from the starter, so the language ` +
142
+ `prompt cannot be added automatically. Add it by hand; see ${GUIDE}.`,
143
+ );
144
+ }
145
+ let out = source;
146
+ for (const [find, replace] of PROMPT_EDITS) out = out.replace(find, replace);
147
+ return out;
148
+ });
149
+ }
150
+
151
+ /** Every file under `dir`, as paths relative to it. */
152
+ function listFiles(dir) {
153
+ const out = [];
154
+ const walk = (current) => {
155
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
156
+ const full = join(current, entry.name);
157
+ if (entry.isDirectory()) walk(full);
158
+ else out.push(relative(dir, full));
159
+ }
160
+ };
161
+ walk(dir);
162
+ return out.sort();
163
+ }
164
+
165
+ const LAYOUT_FILE = /^layout\.(tsx|ts|jsx|js)$/;
166
+
167
+ /** A layout that renders the document itself, so it can serve as a root layout. */
168
+ function isRootLayout(path) {
169
+ return /<html\b|<HtmlShell\b/.test(readFileSync(path, "utf-8"));
170
+ }
171
+
172
+ /** Pages under `appDir` that would be left without a root layout. */
173
+ function pagesOutsideRootLayouts(appDir) {
174
+ const skip = new Set([join(appDir, "p1"), join(appDir, OLD_SEGMENT), join(appDir, NEW_SEGMENT)]);
175
+ const found = [];
176
+ const walk = (current, covered) => {
177
+ const entries = readdirSync(current, { withFileTypes: true });
178
+ const hasRoot =
179
+ covered ||
180
+ (current !== appDir &&
181
+ entries.some((entry) => entry.isFile() && LAYOUT_FILE.test(entry.name) && isRootLayout(join(current, entry.name))));
182
+ for (const entry of entries) {
183
+ const full = join(current, entry.name);
184
+ if (entry.isDirectory()) {
185
+ if (!skip.has(full)) walk(full, hasRoot);
186
+ } else if (/^page\.(tsx|ts|jsx|js|mdx)$/.test(entry.name) && current !== appDir && !hasRoot) {
187
+ found.push(full);
188
+ }
189
+ }
190
+ };
191
+ walk(appDir, false);
192
+ return found;
193
+ }
194
+
195
+ const ROOT_SPECIAL_BLOCKED = ["error", "loading", "template", "default"];
196
+
197
+ function rootSpecialFiles(appDir) {
198
+ return readdirSync(appDir)
199
+ .filter((name) => ROOT_SPECIAL_BLOCKED.includes(name.replace(/\.(tsx|ts|jsx|js)$/, "")))
200
+ .sort();
201
+ }
202
+
203
+ const CODE_FILE = /\.(tsx|ts|jsx|js|mjs|cjs)$/;
204
+ const SKIP_DIRS = new Set(["node_modules", ".next", "dist", "build", "out", "coverage"]);
205
+
206
+ /** Source files outside the moved route that still name its old directory. */
207
+ function filesNamingOldSegment(dir, exclude) {
208
+ const found = [];
209
+ const walk = (current) => {
210
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
211
+ const full = join(current, entry.name);
212
+ if (entry.isDirectory()) {
213
+ if (!entry.name.startsWith(".") && !SKIP_DIRS.has(entry.name) && !exclude.has(full)) walk(full);
214
+ } else if (CODE_FILE.test(entry.name) && !exclude.has(full)) {
215
+ if (readFileSync(full, "utf-8").includes(`${OLD_SEGMENT}/`)) found.push(full);
216
+ }
217
+ }
218
+ };
219
+ walk(dir);
220
+ return found.sort();
221
+ }
222
+
223
+ /** What a customized root layout holds that has to move by hand, and where. */
224
+ export function describeLayoutCustomizations(source) {
225
+ const items = [];
226
+ if (/from\s+["']next\/font/.test(source)) items.push("fonts (next/font) -> components/html-shell.tsx");
227
+ if (/<Script\b|@vercel\/analytics|gtag|googletagmanager/.test(source)) {
228
+ items.push("analytics and scripts -> components/html-shell.tsx");
229
+ }
230
+ const body = source.slice(source.indexOf("<body") === -1 ? 0 : source.indexOf("<body"));
231
+ const providers = [...new Set([...body.matchAll(/<([A-Z][A-Za-z0-9.]*)/g)].map((m) => m[1]))];
232
+ if (providers.length > 0) items.push(`providers and wrappers (${providers.join(", ")}) -> components/html-shell.tsx`);
233
+ if (/export\s+(const\s+metadata|async\s+function\s+generateMetadata|function\s+generateMetadata)/.test(source)) {
234
+ items.push(`metadata -> app/${NEW_SEGMENT}/layout.tsx`);
235
+ }
236
+ if (/metadataBase/.test(source)) items.push(`metadataBase -> app/${NEW_SEGMENT}/layout.tsx`);
237
+ if (/export\s+const\s+viewport/.test(source)) items.push(`viewport -> app/${NEW_SEGMENT}/layout.tsx`);
238
+ return items;
239
+ }
240
+
241
+ function customizedLayoutMessage(source, show) {
242
+ const lines = [
243
+ `${show("app/layout.tsx")} differs from the starter's, so it is not replaced automatically.`,
244
+ `This migration splits it into app/${NEW_SEGMENT}/layout.tsx (the site), app/p1/layout.tsx ` +
245
+ "(the editor) and components/html-shell.tsx (the <html> and <body> both render).",
246
+ ];
247
+ const items = describeLayoutCustomizations(source);
248
+ if (items.length > 0) lines.push("", "To carry across:", ...items.map((item) => ` ${item}`));
249
+ lines.push("", `Make the split by hand following ${GUIDE}.`);
250
+ return lines.join("\n");
251
+ }
252
+
253
+ /** Write `content` at `path` unless an identical file is there; bail on a different one. */
254
+ function carry(writes, path, content, show) {
255
+ if (existsSync(path)) {
256
+ if (sameSource(readFileSync(path, "utf-8"), content)) return;
257
+ throw new BailError(
258
+ `${show(path)} already exists and differs from the starter's. Merge it by hand; see ${GUIDE}.`,
259
+ );
260
+ }
261
+ writes.push([path, content]);
262
+ }
263
+
264
+ /** The files the localized-pages migration carries from the scaffold, as `[path, template]`. */
265
+ function carriedLayout(route, appDir, root) {
266
+ return [
267
+ [join(route.newRoute, "layout.tsx"), `app/${NEW_SEGMENT}/layout.tsx`],
268
+ [join(appDir, "p1", "layout.tsx"), "app/p1/layout.tsx"],
269
+ [join(root, "components", "html-shell.tsx"), "components/html-shell.tsx"],
270
+ ];
271
+ }
272
+
273
+ /**
274
+ * Write the root layouts a finished move lacks, and the HTML shell when a root
275
+ * layout imports it and it is missing. A file that exists is the project's own.
276
+ */
277
+ function carryMissing(writes, route, appDir, root) {
278
+ const [site, editor, shell] = carriedLayout(route, appDir, root);
279
+ for (const [path, rel] of [site, editor]) {
280
+ if (!existsSync(path)) writes.push([path, template(rel)]);
281
+ }
282
+ const usesShell = [site, editor].some(
283
+ ([path, rel]) => /html-shell/.test(existsSync(path) ? readFileSync(path, "utf-8") : template(rel)),
284
+ );
285
+ if (usesShell && !existsSync(shell[0])) writes.push([shell[0], template(shell[1])]);
286
+ }
287
+
288
+ /**
289
+ * Classify the published-page route:
290
+ * - `legacy`: `app/[...puckPath]` exists and the move has not been made
291
+ * - `migrated`: `app/[[...puckPath]]` exists, and the old route and the files
292
+ * the move takes out of `app/` are gone
293
+ * - `leftovers`: `app/[[...puckPath]]` exists, the old route does not, and some
294
+ * of those files remain
295
+ * - `partial`: both routes exist
296
+ * - `absent`: neither exists
297
+ */
298
+ export function detectPublishedRoute(appDir) {
299
+ const oldRoute = join(appDir, OLD_SEGMENT);
300
+ const newRoute = join(appDir, NEW_SEGMENT);
301
+ const hasOld = existsSync(oldRoute);
302
+ const hasNew = existsSync(newRoute);
303
+ if (hasOld && hasNew) return { status: "partial", oldRoute, newRoute };
304
+ if (hasOld) return { status: "legacy", oldRoute, newRoute };
305
+ if (!hasNew) return { status: "absent", oldRoute, newRoute };
306
+ const leftovers = ["page.tsx", "layout.tsx", "not-found.tsx"]
307
+ .map((name) => join(appDir, name))
308
+ .filter((path) => existsSync(path));
309
+ if (leftovers.length > 0) return { status: "leftovers", oldRoute, newRoute, leftovers };
310
+ return { status: "migrated", oldRoute, newRoute };
311
+ }
312
+
313
+ /**
314
+ * Plan the localized-pages migration. Returns `{ writes, removes, warnings }`
315
+ * with every file's final content computed; nothing to write or remove means
316
+ * the route has already moved. Throws BailError on anything it cannot migrate
317
+ * safely; nothing has been written at that point.
318
+ */
319
+ export function planLocalizedPages(dir, appDir) {
320
+ const root = dirname(appDir);
321
+ const show = (path) => relative(dir, path) || path;
322
+ const route = detectPublishedRoute(appDir);
323
+ const writes = [];
324
+ const removes = [];
325
+ const warnings = [];
326
+
327
+ if (route.status === "partial") {
328
+ throw new BailError(
329
+ `Both ${show(route.oldRoute)} and ${show(route.newRoute)} exist, so an earlier run was ` +
330
+ `interrupted or the move was started by hand. Keep ${show(route.newRoute)}: move anything ` +
331
+ `you still need out of ${show(route.oldRoute)}, delete it, then re-run.`,
332
+ );
333
+ }
334
+ if (route.status === "leftovers") {
335
+ throw new BailError(
336
+ [
337
+ `${show(route.newRoute)} exists, but these files the move takes out of ${show(appDir)} are still there:`,
338
+ ...route.leftovers.map((path) => ` ${show(path)}`),
339
+ `An earlier run was interrupted or the move was started by hand. Finish it following ${GUIDE}.`,
340
+ ].join("\n"),
341
+ );
342
+ }
343
+ if (route.status === "absent") {
344
+ throw new BailError(
345
+ `Could not find ${show(route.oldRoute)}/ or ${show(route.newRoute)}/. Run this from your ` +
346
+ `project root, or migrate by hand following ${GUIDE}.`,
347
+ );
348
+ }
349
+
350
+ const routeFile = join(appDir, "p1", "api", "[...p1]", "route.ts");
351
+ if (existsSync(routeFile) && /publicPageSegment:\s*["']\/\[\.\.\.puckPath\]["']/.test(readFileSync(routeFile, "utf-8"))) {
352
+ warnings.push(
353
+ `${show(routeFile)} sets publicPageSegment to "/[...puckPath]". Publishing a route template ` +
354
+ `now has to refresh "/${NEW_SEGMENT}": change it to that, or remove the option to use the ` +
355
+ "SDK's default, which covers both.",
356
+ );
357
+ }
358
+ if (route.status === "migrated") {
359
+ carryMissing(writes, route, appDir, root);
360
+ return { writes, removes, warnings };
361
+ }
362
+
363
+ const files = listFiles(route.oldRoute);
364
+ const special = files.filter((rel) => rel !== "page.tsx" && isRouteSpecial(rel.split(sep).pop()));
365
+ if (special.length > 0) {
366
+ throw new BailError(
367
+ [
368
+ `${show(route.oldRoute)} contains route files whose behavior depends on where they sit:`,
369
+ ...special.map((rel) => ` ${rel}`),
370
+ `app/${NEW_SEGMENT} gets a root layout of its own, so decide where each belongs, move ` +
371
+ `them out of ${show(route.oldRoute)}, then re-run. See ${GUIDE}.`,
372
+ ].join("\n"),
373
+ );
374
+ }
375
+ if (!files.includes("page.tsx")) {
376
+ throw new BailError(`${show(route.oldRoute)} has no page.tsx; migrate it by hand. See ${GUIDE}.`);
377
+ }
378
+
379
+ const pagePath = join(route.oldRoute, "page.tsx");
380
+ if (!sameSource(readFileSync(pagePath, "utf-8"), template(`legacy/app/${OLD_SEGMENT}/page.tsx`))) {
381
+ throw new BailError(
382
+ `${show(pagePath)} differs from the starter's catch-all page. app/${NEW_SEGMENT} serves "/" ` +
383
+ "too, where params.puckPath is undefined, so move it there by hand and check what you " +
384
+ `changed still holds for the home page, then re-run. See ${GUIDE}.`,
385
+ );
386
+ }
387
+
388
+ const publishedPagesPath = join(appDir, "published-pages.tsx");
389
+ if (!existsSync(publishedPagesPath)) {
390
+ throw new BailError(`${show(publishedPagesPath)} not found; this migration needs the createPublishedPage module there. See ${GUIDE}.`);
391
+ }
392
+
393
+ const homePath = join(appDir, "page.tsx");
394
+ if (existsSync(homePath)) {
395
+ if (!sameSource(readFileSync(homePath, "utf-8"), template("legacy/app/page.tsx"))) {
396
+ throw new BailError(
397
+ `${show(homePath)} differs from the starter's home route. app/${NEW_SEGMENT} serves "/" ` +
398
+ "itself, so this file has to go: move anything you added to it into your published " +
399
+ `content or the page client, delete it, then re-run. See ${GUIDE}.`,
400
+ );
401
+ }
402
+ removes.push(homePath);
403
+ }
404
+
405
+ const layoutPath = join(appDir, "layout.tsx");
406
+ if (!existsSync(layoutPath)) {
407
+ throw new BailError(`${show(layoutPath)} not found; create the root layouts by hand. See ${GUIDE}.`);
408
+ }
409
+ const layout = readFileSync(layoutPath, "utf-8");
410
+ if (!LEGACY_LAYOUTS.some((rel) => sameSource(layout, template(rel)))) {
411
+ throw new BailError(customizedLayoutMessage(layout, show));
412
+ }
413
+
414
+ const rootSpecial = rootSpecialFiles(appDir);
415
+ if (rootSpecial.length > 0) {
416
+ throw new BailError(
417
+ [
418
+ `${show(appDir)} has files that need the root layout this migration splits in two:`,
419
+ ...rootSpecial.map((name) => ` ${name}`),
420
+ `Move each into app/${NEW_SEGMENT}/ or app/p1/, then re-run. See ${GUIDE}.`,
421
+ ].join("\n"),
422
+ );
423
+ }
424
+ const orphans = pagesOutsideRootLayouts(appDir);
425
+ if (orphans.length > 0) {
426
+ throw new BailError(
427
+ [
428
+ "These pages would be left without a root layout:",
429
+ ...orphans.map((path) => ` ${show(path)}`),
430
+ `Give them one (see ${GUIDE}), then re-run.`,
431
+ ].join("\n"),
432
+ );
433
+ }
434
+
435
+ const testsDir = join(dir, "__tests__");
436
+ const customizedTests = [];
437
+ for (const [name, versions] of Object.entries(LEGACY_TESTS)) {
438
+ const path = join(testsDir, name);
439
+ if (!existsSync(path)) continue;
440
+ if (versions.includes(sourceHash(readFileSync(path, "utf-8")))) removes.push(path);
441
+ else customizedTests.push(path);
442
+ }
443
+ if (customizedTests.length > 0) {
444
+ throw new BailError(
445
+ [
446
+ "The starter no longer includes these tests, and yours differ from the scaffolded versions:",
447
+ ...customizedTests.map((path) => ` ${show(path)}`),
448
+ `They check the old file layout. Delete them, or rename any you want to keep and update ` +
449
+ `it for app/${NEW_SEGMENT}, then re-run. See ${GUIDE}.`,
450
+ ].join("\n"),
451
+ );
452
+ }
453
+
454
+ // The route moves to a directory at the same depth, so its relative imports hold.
455
+ for (const rel of files) {
456
+ if (rel === "page.tsx") {
457
+ writes.push([join(route.newRoute, rel), template(`app/${NEW_SEGMENT}/page.tsx`)]);
458
+ } else {
459
+ writes.push([join(route.newRoute, rel), readFileSync(join(route.oldRoute, rel))]);
460
+ }
461
+ }
462
+
463
+ const notFoundPath = join(appDir, "not-found.tsx");
464
+ if (existsSync(notFoundPath)) {
465
+ writes.push([join(route.newRoute, "not-found.tsx"), moveImportsOneLevelDeeper(readFileSync(notFoundPath, "utf-8"))]);
466
+ removes.push(notFoundPath);
467
+ }
468
+
469
+ writes.push([publishedPagesPath, rewritePublishedPages(readFileSync(publishedPagesPath, "utf-8"))]);
470
+ removes.push(layoutPath);
471
+ // Last, so a run cut short leaves both routes, which the next run reports.
472
+ removes.push(route.oldRoute);
473
+ for (const [path, rel] of carriedLayout(route, appDir, root)) carry(writes, path, template(rel), show);
474
+
475
+ const stale = filesNamingOldSegment(dir, new Set([publishedPagesPath, ...removes]));
476
+ if (stale.length > 0) {
477
+ warnings.push(
478
+ [
479
+ `These files still name app/${OLD_SEGMENT}/ and need updating to app/${NEW_SEGMENT}/:`,
480
+ ...stale.map((path) => ` ${show(path)}`),
481
+ ].join("\n"),
482
+ );
483
+ }
484
+
485
+ return { writes, removes, warnings };
486
+ }
487
+
488
+ /**
489
+ * Plan the locale-prompt migration: render the saved-language prompt from the
490
+ * page client and carry its files from the scaffold. Nothing to write means the
491
+ * prompt is already there.
492
+ */
493
+ export function planLocalePrompt(dir, appDir) {
494
+ const root = dirname(appDir);
495
+ const show = (path) => relative(dir, path) || path;
496
+ const route = detectPublishedRoute(appDir);
497
+ if (route.status !== "migrated") {
498
+ throw new BailError(
499
+ `The language prompt renders from ${show(route.newRoute)}/client.tsx, which needs the ` +
500
+ `localized-pages migration first. Run \`${COMMAND} localized-pages\`, then re-run this one.`,
501
+ );
502
+ }
503
+
504
+ const clientPath = join(route.newRoute, "client.tsx");
505
+ if (!existsSync(clientPath)) {
506
+ throw new BailError(`${show(clientPath)} not found; add the language prompt by hand. See ${GUIDE}.`);
507
+ }
508
+ const writes = [];
509
+ const client = readFileSync(clientPath, "utf-8");
510
+ const withPrompt = addLocalePrompt(client);
511
+ if (withPrompt !== client) writes.push([clientPath, withPrompt]);
512
+ carry(writes, join(root, "components", "locale-suggestion.tsx"), template("components/locale-suggestion.tsx"), show);
513
+ carry(
514
+ writes,
515
+ join(root, "components", "locale-suggestion.module.css"),
516
+ template("components/locale-suggestion.module.css"),
517
+ show,
518
+ );
519
+ carry(writes, join(root, "lib", "locale-name.ts"), template("lib/locale-name.ts"), show);
520
+ return { writes, removes: [], warnings: [] };
521
+ }
522
+
@@ -3,16 +3,21 @@
3
3
  * dependency — so the SDK's runtime deps stay unchanged.
4
4
  */
5
5
 
6
- import { CHATBOT_MIN_VERSION, MIN_SUITE_VERSION } from "./detect.js";
6
+ import { CHATBOT_MIN_VERSION, LOCALIZATION_MIN_VERSION, MIN_SUITE_VERSION } from "./detect.js";
7
7
 
8
8
  const TAG = "[p1-migrate]";
9
9
 
10
- export function help() {
10
+ export function help(migrations) {
11
+ const names = Object.keys(migrations);
12
+ const width = Math.max(...names.map((name) => name.length)) + 3;
11
13
  console.log(
12
14
  [
13
- "p1-next-sdk migrate — migrate a P1 app to the persistent (editor) layout",
15
+ "p1-next-sdk migrate — update a P1 app's files to what newer P1 packages expect",
14
16
  "",
15
- "Usage: npx @pantheon-systems/p1-next-sdk migrate [options]",
17
+ "Usage: npx @pantheon-systems/p1-next-sdk migrate <migration> [options]",
18
+ "",
19
+ "Migrations:",
20
+ ...names.map((name) => ` ${name.padEnd(width)}${migrations[name].summary}`),
16
21
  "",
17
22
  "Options:",
18
23
  " --dir=<path> Project directory to migrate (default: current directory)",
@@ -23,8 +28,8 @@ export function help() {
23
28
  );
24
29
  }
25
30
 
26
- export function alreadyMigrated() {
27
- console.log(`${TAG} Already on the (editor) layout — nothing to do.`);
31
+ export function alreadyMigrated(title) {
32
+ console.log(`${TAG} Nothing to do: this project already has ${title}.`);
28
33
  }
29
34
 
30
35
  export function noGitRepo() {
@@ -34,18 +39,28 @@ export function noGitRepo() {
34
39
  );
35
40
  }
36
41
 
37
- export function versionsUnverified() {
42
+ export function versionsUnverified(command) {
38
43
  console.log(
39
44
  `${TAG} Could not read installed @pantheon-systems/* versions — skipping the version check.`,
40
45
  );
41
- console.log(
42
- `${TAG} Make sure your dependencies are installed and on ${MIN_SUITE_VERSION} or newer.`,
43
- );
44
- console.log(
45
- `${TAG} The chatbot step is attempted without verification, and what it writes needs ` +
46
- `${CHATBOT_MIN_VERSION} or newer. If your editor ends up unable to resolve ` +
47
- "@pantheon-systems/p1-next-sdk/chatbot, that is the version to upgrade to.",
48
- );
46
+ if (command === "editor-layout") {
47
+ console.log(
48
+ `${TAG} Make sure your dependencies are installed and on ${MIN_SUITE_VERSION} or newer.`,
49
+ );
50
+ console.log(
51
+ `${TAG} The chatbot step is attempted without verification, and what it writes needs ` +
52
+ `${CHATBOT_MIN_VERSION} or newer. If your editor ends up unable to resolve ` +
53
+ "@pantheon-systems/p1-next-sdk/chatbot, that is the version to upgrade to.",
54
+ );
55
+ } else {
56
+ console.log(
57
+ `${TAG} Make sure your dependencies are installed and on ${LOCALIZATION_MIN_VERSION} or newer.`,
58
+ );
59
+ }
60
+ }
61
+
62
+ export function warning(message) {
63
+ console.log(`${TAG} Warning: ${message}`);
49
64
  }
50
65
 
51
66
  export function chatbotStepSkipped(version) {
@@ -60,16 +75,16 @@ export function chatbotStepSkipped(version) {
60
75
  );
61
76
  }
62
77
 
63
- export function dryRunPlan(writePaths, oldDir) {
64
- console.log(`${TAG} Dry run — no files written. Planned changes:`);
65
- for (const p of writePaths) console.log(` write ${p}`);
66
- console.log(` remove ${oldDir}`);
78
+ export function dryRunPlan({ command, writes, removes }) {
79
+ console.log(`${TAG} Dry run — no files written. Planned changes for ${command}:`);
80
+ for (const p of writes) console.log(` write ${p}`);
81
+ for (const p of removes) console.log(` remove ${p}`);
67
82
  }
68
83
 
69
- export function success(writePaths, oldDir) {
70
- console.log(`${TAG} Migrated to the persistent (editor) layout:`);
71
- for (const p of writePaths) console.log(` wrote ${p}`);
72
- console.log(` removed ${oldDir}`);
84
+ export function success({ command, writes, removes }) {
85
+ console.log(`${TAG} Applied ${command}:`);
86
+ for (const p of writes) console.log(` wrote ${p}`);
87
+ for (const p of removes) console.log(` removed ${p}`);
73
88
  console.log(`${TAG} Review the diff and commit when it looks right.`);
74
89
  }
75
90
 
@@ -0,0 +1,29 @@
1
+ import "../styles.css";
2
+ import type { Metadata } from "next";
3
+ import { HtmlShell } from "../../components/html-shell";
4
+ import { published } from "../published-pages";
5
+
6
+ const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;
7
+
8
+ // A page-level openGraph replaces (not merges) this one, so buildPageMetadata
9
+ // re-declares og:type and the env site-name fallback; this covers routes that
10
+ // return no openGraph (e.g. not-found early returns).
11
+ export const metadata: Metadata = {
12
+ ...(siteUrl ? { metadataBase: new URL(siteUrl) } : {}),
13
+ openGraph: {
14
+ type: "website",
15
+ siteName: process.env.NEXT_PUBLIC_SITE_NAME,
16
+ },
17
+ };
18
+
19
+ /** Root layout for the site: `<html lang>` is the language of the page shown. */
20
+ export default async function SiteLayout({
21
+ children,
22
+ params,
23
+ }: {
24
+ children: React.ReactNode;
25
+ params: Promise<{ puckPath?: string[] }>;
26
+ }) {
27
+ const lang = (await published.getDocumentLanguage({ params })) ?? "en";
28
+ return <HtmlShell lang={lang}>{children}</HtmlShell>;
29
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Optional catch-all route that renders the home page and every other
3
+ * user-facing page generated by Puck.
4
+ *
5
+ * The pipeline lives in the SDK — see createPublishedPage in
6
+ * app/published-pages.tsx for what this route is made of.
7
+ */
8
+
9
+ import { published } from "../published-pages";
10
+
11
+ /**
12
+ * Backstop only: publishing calls revalidatePath for the affected routes, so
13
+ * cached pages normally refresh the moment their content changes. This bounds
14
+ * how long an edit made outside that path (a direct API write, a restored
15
+ * branch) can stay stale.
16
+ *
17
+ * Must stay a literal here: Next.js statically analyzes segment-config exports,
18
+ * so a value re-exported from the factory would go undetected.
19
+ */
20
+ export const revalidate = 300;
21
+
22
+ export const generateStaticParams = published.generateStaticParams;
23
+ export const generateMetadata = published.generateMetadata;
24
+ export default published.Page;