@gradial/aci 0.1.46 → 0.1.48

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 (61) hide show
  1. package/README.md +4 -4
  2. package/dist/astro/error-page.d.ts +56 -0
  3. package/dist/astro/error-page.js +79 -0
  4. package/dist/astro/index.d.ts +4 -0
  5. package/dist/astro/index.js +9 -0
  6. package/dist/cli/emit-error-pages.d.mts +39 -0
  7. package/dist/cli/emit-error-pages.mjs +402 -0
  8. package/dist/collect/aci.js +1 -1
  9. package/dist/collect/aci.js.sha256 +1 -1
  10. package/dist/collect/webvitals.d.ts +3 -0
  11. package/dist/collect/webvitals.js +21 -11
  12. package/dist/content/default-error-page-html.d.ts +2 -0
  13. package/dist/content/default-error-page-html.js +6 -0
  14. package/dist/content/default-error-page.d.ts +23 -0
  15. package/dist/content/default-error-page.js +34 -0
  16. package/dist/content/error-page-kind.d.ts +57 -0
  17. package/dist/content/error-page-kind.js +106 -0
  18. package/dist/content/error-pages.d.ts +88 -0
  19. package/dist/content/error-pages.js +120 -0
  20. package/dist/content/index.d.ts +2 -0
  21. package/dist/content/index.js +2 -0
  22. package/dist/content/types.d.ts +12 -0
  23. package/dist/edge/personalization-core.js +6 -2
  24. package/dist/next/config.js +17 -0
  25. package/dist/next/error-page-instrumentation.d.ts +23 -0
  26. package/dist/next/error-page-instrumentation.js +36 -0
  27. package/dist/next/error-page-marker.d.ts +11 -0
  28. package/dist/next/error-page-marker.js +20 -0
  29. package/dist/next/error-pages.d.ts +52 -0
  30. package/dist/next/error-pages.js +94 -0
  31. package/dist/next/error-seat-payload.d.ts +33 -0
  32. package/dist/next/error-seat-payload.js +143 -0
  33. package/dist/next/error-seat.d.ts +57 -0
  34. package/dist/next/error-seat.js +83 -0
  35. package/dist/next/index.d.ts +4 -0
  36. package/dist/next/index.js +8 -0
  37. package/package.json +14 -8
  38. package/src/cli/emit-error-pages.mjs +424 -0
  39. package/templates/astro/template/package.json.tmpl +1 -1
  40. package/templates/astro/template/src/aci/error-page-instrumentation.mjs +33 -0
  41. package/templates/astro/template/src/pages/404.astro +54 -0
  42. package/templates/astro/template/src/pages/500.astro +53 -0
  43. package/templates/astro/template/src/pages/[...slug].astro +15 -2
  44. package/templates/common/.agents/skills/authoring/SKILL.md +71 -0
  45. package/templates/common/.content/config/robots.txt +4 -0
  46. package/templates/common/.content/config/site.json.tmpl +4 -0
  47. package/templates/common/.content/pages/404/_index.json +31 -0
  48. package/templates/common/.content/pages/error/_index.json +31 -0
  49. package/templates/common/.content/schemas/site.schema.json +9 -0
  50. package/templates/common/starter-content/.content/config/robots.txt +2 -0
  51. package/templates/common/starter-content/.content/config/site.json +4 -0
  52. package/templates/common/starter-content/.content/pages/404/_index.json +31 -0
  53. package/templates/common/starter-content/.content/pages/about/_index.json +3 -6
  54. package/templates/common/starter-content/.content/pages/error/_index.json +31 -0
  55. package/templates/common/starter-content/.content/pages/home/_index.json +10 -19
  56. package/templates/common/starter-content/.content/schemas/site.schema.json +9 -0
  57. package/templates/nextjs/template/package.json.tmpl +1 -1
  58. package/templates/nextjs/template/src/aci/error-page-instrumentation.d.mts +4 -0
  59. package/templates/nextjs/template/src/aci/error-page-instrumentation.mjs +38 -0
  60. package/templates/nextjs/template/src/app/error.tsx +18 -0
  61. package/templates/nextjs/template/src/app/not-found.tsx +13 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Agentic Content Infrastructure SDK
2
2
 
3
- `@gradial/aci` `0.1.45` is a pre-1.0 public-surface reset for the ACI
3
+ `@gradial/aci` `0.1.48` is a pre-1.0 public-surface reset for the ACI
4
4
  client SDK. Breaking changes from the old `0.1.x` accidental surface are
5
5
  intentional: the root import is framework-neutral, framework runtime behavior is
6
6
  behind explicit subpaths, and the first required customer path is React/Next.
@@ -8,7 +8,7 @@ behind explicit subpaths, and the first required customer path is React/Next.
8
8
  ## Install
9
9
 
10
10
  ```bash
11
- npm install @gradial/aci@0.1.45 zod@^4
11
+ npm install @gradial/aci@0.1.48 zod@^4
12
12
  ```
13
13
 
14
14
  ## Root Import
@@ -85,13 +85,13 @@ go through an app-owned HTTP endpoint backed server-side by a `ContentProvider`.
85
85
  The first RC scaffold path is Next:
86
86
 
87
87
  ```bash
88
- npx @gradial/aci@0.1.45 init my-site --template next-starter
88
+ npx @gradial/aci@0.1.48 init my-site --template next-starter
89
89
  ```
90
90
 
91
91
  List available templates:
92
92
 
93
93
  ```bash
94
- npx @gradial/aci@0.1.45 init --list
94
+ npx @gradial/aci@0.1.48 init --list
95
95
  ```
96
96
 
97
97
  ## Personalization: The One-Tag Install
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Astro error-page render helper (authorable-error-pages REQ-7 / REQ-11 /
3
+ * D-10 / D-11; 02-design "SDK core"). The Astro counterpart of the Next
4
+ * seams in `src/next/error-pages.tsx`: resolve the page bound by
5
+ * `site.json#errorPages[kind]` and load it through the normal page pipeline
6
+ * (`getPageData`) so the template's `404.astro`/`500.astro` stay thin —
7
+ * the spike's hand-rolled binding resolution and siteConfig casting live
8
+ * here instead (spike A kill list).
9
+ *
10
+ * Never throws: an error surface must not crash and must not re-enter the
11
+ * failing system (ANTI-2). Any failure — no bindings (REQ-4 warn posture),
12
+ * unreadable content, a bound page missing at render time — degrades to the
13
+ * shipped branded-neutral default fragment with the problem surfaced via
14
+ * console.warn.
15
+ *
16
+ * REQ-11: error pages are base-audience with no personalization, so the
17
+ * returned page data always carries empty collect/assignment tags.
18
+ */
19
+ import { type AstroGlobal, type PageData } from './page.js';
20
+ import { type ErrorPageKind, type ErrorPagePush, type ErrorPageType } from '../content/error-pages.js';
21
+ import type { KernelRouteMetadata } from '../content/types.js';
22
+ export interface AstroErrorPageData {
23
+ kind: ErrorPageKind;
24
+ /** D-14 page_type for the seat's instrumentation script. */
25
+ pageType: ErrorPageType;
26
+ /**
27
+ * Pre-rendered D-14 analytics `<script>` tag: the site's push function
28
+ * (`options.pushErrorPageView`, D-15 — normally the tenant-owned
29
+ * `src/aci/error-page-instrumentation.mjs`; the SDK default when omitted)
30
+ * serialized via `serializeErrorPageInstrumentation`. The seat injects it
31
+ * via `<Fragment set:html={...}>` — Astro serves real HTML documents, so
32
+ * the inline script executes.
33
+ */
34
+ instrumentationTag: string;
35
+ /**
36
+ * The bound page loaded through the normal pipeline, with collect and
37
+ * assignment tags suppressed (REQ-11). Null when the shipped default
38
+ * applies — render `fallbackHtml` instead.
39
+ */
40
+ data: PageData | null;
41
+ /** Shipped branded-neutral default fragment (REQ-4) when `data` is null. */
42
+ fallbackHtml: string | null;
43
+ /** Document metadata for the layout shell, valid in either branch. */
44
+ meta: KernelRouteMetadata;
45
+ }
46
+ /**
47
+ * Resolves and loads the error page bound to `kind` for Astro's native
48
+ * error seats (`404.astro` / `500.astro`). `astro` is the seat's Astro
49
+ * global; the bound route's content is loaded as if it were the requested
50
+ * route, so static builds emit it into `dist/404.html`/`dist/500.html` and
51
+ * server output renders it at error time from local compiled content — no
52
+ * CMS fetch on the failing path (ANTI-2).
53
+ */
54
+ export declare function getErrorPageData(astro: AstroGlobal, kind: ErrorPageKind, options?: {
55
+ pushErrorPageView?: ErrorPagePush;
56
+ }): Promise<AstroErrorPageData>;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Astro error-page render helper (authorable-error-pages REQ-7 / REQ-11 /
3
+ * D-10 / D-11; 02-design "SDK core"). The Astro counterpart of the Next
4
+ * seams in `src/next/error-pages.tsx`: resolve the page bound by
5
+ * `site.json#errorPages[kind]` and load it through the normal page pipeline
6
+ * (`getPageData`) so the template's `404.astro`/`500.astro` stay thin —
7
+ * the spike's hand-rolled binding resolution and siteConfig casting live
8
+ * here instead (spike A kill list).
9
+ *
10
+ * Never throws: an error surface must not crash and must not re-enter the
11
+ * failing system (ANTI-2). Any failure — no bindings (REQ-4 warn posture),
12
+ * unreadable content, a bound page missing at render time — degrades to the
13
+ * shipped branded-neutral default fragment with the problem surfaced via
14
+ * console.warn.
15
+ *
16
+ * REQ-11: error pages are base-audience with no personalization, so the
17
+ * returned page data always carries empty collect/assignment tags.
18
+ */
19
+ import { getPageData } from './page.js';
20
+ import { defaultPushErrorPageView, errorPageType, resolveErrorPage, serializeErrorPageInstrumentation, } from '../content/error-pages.js';
21
+ import { defaultErrorPageFragmentHtml } from '../content/default-error-page.js';
22
+ const FALLBACK_META = {
23
+ notFound: {
24
+ title: 'Page not found',
25
+ description: 'The page you requested does not exist.',
26
+ },
27
+ catchAll: {
28
+ title: 'Something went wrong',
29
+ description: 'The page you requested could not be served right now.',
30
+ },
31
+ };
32
+ /**
33
+ * Resolves and loads the error page bound to `kind` for Astro's native
34
+ * error seats (`404.astro` / `500.astro`). `astro` is the seat's Astro
35
+ * global; the bound route's content is loaded as if it were the requested
36
+ * route, so static builds emit it into `dist/404.html`/`dist/500.html` and
37
+ * server output renders it at error time from local compiled content — no
38
+ * CMS fetch on the failing path (ANTI-2).
39
+ */
40
+ export async function getErrorPageData(astro, kind, options = {}) {
41
+ const pageType = errorPageType(kind);
42
+ const instrumentationTag = serializeErrorPageInstrumentation(options.pushErrorPageView ?? defaultPushErrorPageView, kind);
43
+ try {
44
+ const { FileContentProvider } = await import('../providers/file.js');
45
+ const siteConfig = await new FileContentProvider().getSiteConfig();
46
+ const resolved = await resolveErrorPage(kind, siteConfig);
47
+ for (const warning of resolved.warnings) {
48
+ console.warn(`[aci error-pages] ${warning}`);
49
+ }
50
+ if (resolved.route) {
51
+ const slug = resolved.route.replace(/^\/+|\/+$/g, '');
52
+ const data = await getPageData({
53
+ params: { slug },
54
+ request: astro.request,
55
+ url: astro.url,
56
+ });
57
+ return {
58
+ kind,
59
+ pageType,
60
+ instrumentationTag,
61
+ // Base audience, no personalization on error surfaces (REQ-11).
62
+ data: { ...data, collectTag: '', assignmentsTag: '' },
63
+ fallbackHtml: null,
64
+ meta: data.meta,
65
+ };
66
+ }
67
+ }
68
+ catch (error) {
69
+ console.warn(`[aci error-pages] bound ${kind} page failed to load; serving the shipped default: ${String(error)}`);
70
+ }
71
+ return {
72
+ kind,
73
+ pageType,
74
+ instrumentationTag,
75
+ data: null,
76
+ fallbackHtml: defaultErrorPageFragmentHtml(),
77
+ meta: { ...FALLBACK_META[kind], siteName: 'Gradial' },
78
+ };
79
+ }
@@ -36,6 +36,10 @@ export declare function getGradialStaticPaths(): Promise<Array<{
36
36
  }>>;
37
37
  export declare function getPageRuntimeRenderInput(request: Request): RenderInput | null;
38
38
  export { getPageData, type PageData, type AstroGlobal, type GetPageDataOptions, } from './page.js';
39
+ export { getErrorPageData, type AstroErrorPageData, } from './error-page.js';
40
+ export { errorPageType, type ErrorPageType } from '../content/error-pages.js';
41
+ export type { ErrorPageKind } from '../content/error-pages.js';
42
+ export { PageNotFoundError } from '../content/provider.js';
39
43
  export { createRegistry, registryLookup } from '../registry.js';
40
44
  export type { Registry, RegistryEntry, AnyComponent } from '../registry.js';
41
45
  export type { BlockRef } from '../types/block-ref.js';
@@ -37,6 +37,15 @@ export function getPageRuntimeRenderInput(request) {
37
37
  // ---------------------------------------------------------------------------
38
38
  export { getPageData, } from './page.js';
39
39
  // ---------------------------------------------------------------------------
40
+ // Authorable error pages (specs/features/authorable-error-pages, REQ-7/D-10)
41
+ // — the seats' resolve+render helper, and PageNotFoundError so the catch-all
42
+ // can map content misses to a 404 response in server output.
43
+ // ---------------------------------------------------------------------------
44
+ export { getErrorPageData, } from './error-page.js';
45
+ // Single definition of the kind→page_type mapping (quorum SIMPLE-005).
46
+ export { errorPageType } from '../content/error-pages.js';
47
+ export { PageNotFoundError } from '../content/provider.js';
48
+ // ---------------------------------------------------------------------------
40
49
  // Registry helpers
41
50
  // ---------------------------------------------------------------------------
42
51
  export { createRegistry, registryLookup } from '../registry.js';
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * D-15 policy resolution for the 500.html instrumentation tag (page_type
4
+ * "error"; self-contained inline delivery — this copy is a real static
5
+ * document where inline scripts execute). Convention path: the tenant-owned
6
+ * `src/aci/error-page-instrumentation.mjs` exporting `pushErrorPageView` is
7
+ * serialized via the SDK mechanism; absent → the SDK default tag. A module
8
+ * that EXISTS but fails to import or lacks the export fails the emit loudly:
9
+ * a typo'd policy module silently reverting to the default is the failure
10
+ * mode D-15 guards against. The source used is logged either way.
11
+ *
12
+ * Exported for unit tests; `content` injects the SDK content functions so
13
+ * tests stay dist-free (at runtime they arrive through the same lazy dist
14
+ * import every other SDK internal uses here, sdkContent).
15
+ */
16
+ export function resolveInstrumentationTag(root: string | undefined, content: any): Promise<any>;
17
+ /**
18
+ * D-16 prepare-phase artifact: serializes BOTH kinds' instrumentation tags
19
+ * (tenant module when present, SDK default otherwise) into
20
+ * error-pages/instrumentation.json under the compiled content root. The
21
+ * AWS-lane code capsule packs source/.aci/compiled/**, so the Go publish
22
+ * materializer reads this file from the capsule and stamps the kind-matching
23
+ * tag into the CDN error artifacts — the tag crosses the JS→Go boundary as
24
+ * data. Serialization failures (bind/method-shorthand exports, FIND-006)
25
+ * throw before anything is written.
26
+ *
27
+ * Exported for unit tests; `content` and `outRoot` are injected there like
28
+ * resolveInstrumentationTag's `content`.
29
+ */
30
+ export function writeInstrumentationArtifact(root: string | undefined, content: any, outRoot?: string): Promise<string>;
31
+ /**
32
+ * Appends the D-14 instrumentation script tag and the generation marker
33
+ * before </body>. Exported for unit tests (the tag is a parameter so the
34
+ * function stays synchronous and dist-free there). Throws when the document
35
+ * has no </body> (quorum BUG-003): writing an UNMARKED 500.html would poison
36
+ * every later build via the skip-if-present contract, so the emit fails
37
+ * loudly instead.
38
+ */
39
+ export function stampInstrumentation(html: any, instrumentationTag: any): any;
@@ -0,0 +1,402 @@
1
+ #!/usr/bin/env node
2
+ // Authorable error pages — build integration (spec:
3
+ // specs/features/authorable-error-pages, T3/T11; REQ-10/REQ-11/REQ-14, D-9,
4
+ // D-16).
5
+ //
6
+ // Two phases. The Next template wires both around `next build`; the Astro
7
+ // template runs only `prepare` before `astro build` (its 404/500 seats
8
+ // render through the framework, but the D-16 instrumentation artifact must
9
+ // still reach the compiled content root for the AWS lane):
10
+ //
11
+ // prepare (before `next build`)
12
+ // Ensures compiled content exists at .aci/compiled so withAci() can
13
+ // serialize the bound catchAll page for the client-only error seat
14
+ // (D-9). Compiles ./.content via the platform CLI when needed; when
15
+ // neither compiled content nor authored content exists, it warns and
16
+ // leaves the shipped default in play (REQ-4, warn posture). Then writes
17
+ // error-pages/instrumentation.json (both kinds' serialized tags) into
18
+ // the compiled content root so the tag crosses the JS→Go boundary as
19
+ // data: the AWS-lane code capsule packs source/.aci/compiled/** and the
20
+ // Go publish materializer stamps the kind-matching tag into the CDN
21
+ // error artifacts (D-16). An unserializable tenant push fails the build
22
+ // loudly here (delta FIND-006).
23
+ //
24
+ // emit (after `next build`)
25
+ // Materializes `public/500.html` from the page bound to
26
+ // site.json#errorPages.catchAll by booting the standalone build,
27
+ // fetching the bound route, and post-processing the document. Boot-and-
28
+ // fetch beats re-rendering the page here because the standalone server
29
+ // is the only renderer that produces the document exactly as served
30
+ // (layout shell, resolved fragments, RSC-injected head and styles).
31
+ // Post-processing:
32
+ // - all script tags and preload/prefetch links stripped — this
33
+ // removes the collect and assignment tags (REQ-11) along with the
34
+ // framework runtime, which is useless in a statically served copy;
35
+ // - same-origin stylesheets inlined from .next/static (REQ-14 spirit:
36
+ // inline styles; note @font-face/image URLs inside the CSS keep
37
+ // their same-origin paths — this copy is served by the Vercel
38
+ // platform on the deployment that owns those assets);
39
+ // - one self-contained inline script appended pushing the D-14
40
+ // `page_view` (page_type "error") — a static document executes
41
+ // inline scripts, unlike the flight-rendered not-found seat. The
42
+ // push body is site policy (D-15): the tenant-owned
43
+ // src/aci/error-page-instrumentation.mjs when present, the SDK
44
+ // default otherwise;
45
+ // - hard size budget: ≤150 KB raw (REQ-14) — exceeding it fails the
46
+ // build; trimming the design system or falling back to system
47
+ // fonts is the sanctioned escape hatch.
48
+ // Skips when the site already provides its own public/500.html (a file
49
+ // without the generation marker); regenerates its own prior output.
50
+ // Absent bindings emit the shipped branded-neutral default (REQ-4).
51
+ // Vercel picks static per-status files out of the build output
52
+ // ("file presence = configuration"); on the current Pro plan the file
53
+ // serves app-level 500s only and lights up for platform 5xx on a plan
54
+ // upgrade (REQ-10, P-1).
55
+ //
56
+ // Usage: node ./node_modules/@gradial/aci/src/cli/emit-error-pages.mjs <prepare|emit>
57
+ import { execFileSync, spawn } from 'node:child_process';
58
+ import fs from 'node:fs';
59
+ import net from 'node:net';
60
+ import path from 'node:path';
61
+ import { fileURLToPath, pathToFileURL } from 'node:url';
62
+ const MARKER = '<!-- aci:error-pages generated -->';
63
+ const SIZE_BUDGET = 150 * 1024;
64
+ const BOOT_DEADLINE_MS = 60_000;
65
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
66
+ const siteRoot = process.cwd();
67
+ const contentRoot = path.resolve(siteRoot, process.env.ACI_CONTENT_ROOT || '.aci/compiled');
68
+ function log(message) {
69
+ console.log(`[aci error-pages] ${message}`);
70
+ }
71
+ function warn(message) {
72
+ console.warn(`\n[aci error-pages] WARNING: ${message}\n`);
73
+ }
74
+ function fail(message) {
75
+ console.error(`\n[aci error-pages] ERROR: ${message}\n`);
76
+ process.exit(1);
77
+ }
78
+ async function sdkContent() {
79
+ return await import(pathToFileURL(path.join(packageRoot, 'dist', 'content', 'index.js')).href);
80
+ }
81
+ function hasCompiledContent() {
82
+ return fs.existsSync(path.join(contentRoot, 'manifest.json'));
83
+ }
84
+ // ---------------------------------------------------------------------------
85
+ // prepare
86
+ // ---------------------------------------------------------------------------
87
+ async function prepare() {
88
+ if (hasCompiledContent()) {
89
+ log(`compiled content present at ${contentRoot}`);
90
+ }
91
+ else {
92
+ const authored = path.join(siteRoot, '.content');
93
+ if (!fs.existsSync(authored)) {
94
+ warn(`neither compiled content (${contentRoot}) nor authored content (./.content) exists; `
95
+ + 'the error seat and 500.html will serve the shipped default page (REQ-4)');
96
+ }
97
+ else {
98
+ log('compiling ./.content for the error-page build steps');
99
+ execFileSync('node', [path.join(packageRoot, 'bin', 'aci.js'), 'content', 'compile', '--content', authored, '--out', contentRoot], { cwd: siteRoot, stdio: 'inherit' });
100
+ }
101
+ }
102
+ // D-16: the instrumentation artifact rides the compiled content root into
103
+ // the AWS-lane code capsule (source/.aci/compiled/**). Written even when
104
+ // content is absent — the tenant policy module is independent of authored
105
+ // content, and an artifact the Go materializer never receives silently
106
+ // degrades to the default tags (the exact gap D-16 closes).
107
+ try {
108
+ await writeInstrumentationArtifact();
109
+ }
110
+ catch (error) {
111
+ fail(error.message);
112
+ }
113
+ }
114
+ // ---------------------------------------------------------------------------
115
+ // emit
116
+ // ---------------------------------------------------------------------------
117
+ async function resolveCatchAllRoute() {
118
+ const { resolveErrorPageBindings, defaultErrorPageHtml, errorPagePostureFromEnv } = await sdkContent();
119
+ // D-5 posture: the one shared config surface (ACI_ERROR_PAGES_POSTURE);
120
+ // unknown values fail closed here just like the Go stack.
121
+ let posture;
122
+ try {
123
+ posture = errorPagePostureFromEnv();
124
+ }
125
+ catch (error) {
126
+ fail(error.message);
127
+ }
128
+ if (!hasCompiledContent()) {
129
+ if (posture === 'enforce') {
130
+ fail(`no compiled content at ${contentRoot}; the enforce posture fails closed (D-5)`);
131
+ }
132
+ warn(`no compiled content at ${contentRoot}; emitting the shipped default 500.html (REQ-4)`);
133
+ return { route: null, defaultHtml: defaultErrorPageHtml() };
134
+ }
135
+ const { FileContentProvider } = await import(pathToFileURL(path.join(packageRoot, 'dist', 'providers', 'file.js')).href);
136
+ const provider = new FileContentProvider(contentRoot);
137
+ const siteConfig = await provider.getSiteConfig();
138
+ const resolution = await resolveErrorPageBindings(siteConfig, { source: provider, posture });
139
+ if (resolution.errors.length > 0) {
140
+ fail(`errorPages bindings are invalid (REQ-5, fail closed):\n- ${resolution.errors.join('\n- ')}`);
141
+ }
142
+ for (const warning of resolution.warnings)
143
+ warn(warning);
144
+ if (resolution.defaulted || !resolution.bindings) {
145
+ return { route: null, defaultHtml: defaultErrorPageHtml() };
146
+ }
147
+ return { route: resolution.bindings.catchAll, defaultHtml: defaultErrorPageHtml() };
148
+ }
149
+ async function freePort() {
150
+ return new Promise((resolve, reject) => {
151
+ const server = net.createServer();
152
+ server.unref();
153
+ server.on('error', reject);
154
+ server.listen(0, '127.0.0.1', () => {
155
+ const { port } = server.address();
156
+ server.close(() => resolve(port));
157
+ });
158
+ });
159
+ }
160
+ async function fetchRenderedRoute(route) {
161
+ const serverPath = path.join(siteRoot, '.next', 'standalone', 'server.js');
162
+ if (!fs.existsSync(serverPath)) {
163
+ fail(`${serverPath} missing — the emit phase must run after \`next build\` (withAci uses standalone output)`);
164
+ }
165
+ const port = await freePort();
166
+ const logChunks = [];
167
+ const child = spawn('node', [serverPath], {
168
+ cwd: siteRoot,
169
+ detached: true,
170
+ stdio: ['ignore', 'pipe', 'pipe'],
171
+ env: {
172
+ ...process.env,
173
+ NODE_ENV: 'production',
174
+ PORT: String(port),
175
+ HOSTNAME: '127.0.0.1',
176
+ ACI_CONTENT_PROVIDER: 'file',
177
+ ACI_CONTENT_ROOT: contentRoot,
178
+ },
179
+ });
180
+ child.stdout.on('data', (c) => logChunks.push(String(c)));
181
+ child.stderr.on('data', (c) => logChunks.push(String(c)));
182
+ const exited = new Promise((resolve) => {
183
+ child.on('exit', resolve);
184
+ child.on('error', (error) => {
185
+ logChunks.push(`spawn failed: ${error.message}\n`);
186
+ resolve(null);
187
+ });
188
+ });
189
+ try {
190
+ const url = `http://127.0.0.1:${port}${route}`;
191
+ const start = Date.now();
192
+ let last = 'no attempt made';
193
+ while (Date.now() - start < BOOT_DEADLINE_MS) {
194
+ try {
195
+ const response = await fetch(url, { redirect: 'follow' });
196
+ if (response.status === 200)
197
+ return await response.text();
198
+ last = `status ${response.status}`;
199
+ }
200
+ catch (error) {
201
+ last = error.message;
202
+ }
203
+ await new Promise((r) => setTimeout(r, 500));
204
+ }
205
+ fail(`GET ${url} did not render within ${BOOT_DEADLINE_MS}ms (last: ${last})\n--- server output ---\n${logChunks.join('').slice(-4000)}`);
206
+ return '';
207
+ }
208
+ finally {
209
+ const killGroup = (signal) => {
210
+ if (!child.pid)
211
+ return;
212
+ try {
213
+ process.kill(-child.pid, signal);
214
+ }
215
+ catch { /* gone */ }
216
+ };
217
+ killGroup('SIGTERM');
218
+ const killTimer = setTimeout(() => killGroup('SIGKILL'), 10_000);
219
+ await exited;
220
+ clearTimeout(killTimer);
221
+ killGroup('SIGKILL');
222
+ }
223
+ }
224
+ function inlineStylesheets(html) {
225
+ return html.replace(/<link\b[^>]*rel="stylesheet"[^>]*>/gi, (tag) => {
226
+ const href = tag.match(/href="([^"]+)"/i)?.[1];
227
+ if (!href || !href.startsWith('/_next/')) {
228
+ warn(`dropping non-inlinable stylesheet ${href ?? '<unknown>'} from 500.html (self-containment, REQ-14)`);
229
+ return '';
230
+ }
231
+ const cssPath = path.join(siteRoot, '.next', href.replace(/^\/_next\//, ''));
232
+ if (!fs.existsSync(cssPath)) {
233
+ warn(`stylesheet ${href} not found in .next output; dropping it from 500.html`);
234
+ return '';
235
+ }
236
+ return `<style>${fs.readFileSync(cssPath, 'utf8')}</style>`;
237
+ });
238
+ }
239
+ // Relative convention path of the tenant-owned instrumentation policy
240
+ // module (D-15, code-organization R-14).
241
+ const INSTRUMENTATION_MODULE = path.join('src', 'aci', 'error-page-instrumentation.mjs');
242
+ /**
243
+ * D-15 policy resolution for the 500.html instrumentation tag (page_type
244
+ * "error"; self-contained inline delivery — this copy is a real static
245
+ * document where inline scripts execute). Convention path: the tenant-owned
246
+ * `src/aci/error-page-instrumentation.mjs` exporting `pushErrorPageView` is
247
+ * serialized via the SDK mechanism; absent → the SDK default tag. A module
248
+ * that EXISTS but fails to import or lacks the export fails the emit loudly:
249
+ * a typo'd policy module silently reverting to the default is the failure
250
+ * mode D-15 guards against. The source used is logged either way.
251
+ *
252
+ * Exported for unit tests; `content` injects the SDK content functions so
253
+ * tests stay dist-free (at runtime they arrive through the same lazy dist
254
+ * import every other SDK internal uses here, sdkContent).
255
+ */
256
+ export async function resolveInstrumentationTag(root = siteRoot, content) {
257
+ const sdk = content ?? (await sdkContent());
258
+ const push = await resolveInstrumentationPush(root);
259
+ if (!push)
260
+ return sdk.errorPageInstrumentationTag('catchAll');
261
+ return sdk.serializeErrorPageInstrumentation(push, 'catchAll');
262
+ }
263
+ /**
264
+ * Resolves the tenant policy module's push function by the D-15 convention
265
+ * path. Absent module → null (callers fall back to the SDK default); a
266
+ * module that exists but fails to import or lacks the export throws — a
267
+ * typo'd policy module silently reverting to the default is the failure
268
+ * mode D-15 guards against. The source used is logged either way.
269
+ */
270
+ async function resolveInstrumentationPush(root = siteRoot) {
271
+ const modulePath = path.join(root, INSTRUMENTATION_MODULE);
272
+ if (!fs.existsSync(modulePath)) {
273
+ log(`instrumentation source: SDK default (no ${INSTRUMENTATION_MODULE})`);
274
+ return null;
275
+ }
276
+ let policy;
277
+ try {
278
+ policy = await import(pathToFileURL(modulePath).href);
279
+ }
280
+ catch (error) {
281
+ throw new Error(`${INSTRUMENTATION_MODULE} exists but failed to import: ${error.message}\n`
282
+ + 'A broken policy module must not silently revert to the SDK default (D-15); '
283
+ + 'fix the module or delete it to use the default.');
284
+ }
285
+ if (typeof policy.pushErrorPageView !== 'function') {
286
+ throw new Error(`${INSTRUMENTATION_MODULE} does not export a pushErrorPageView function (D-15 policy contract); `
287
+ + 'export one or delete the file to use the SDK default.');
288
+ }
289
+ log(`instrumentation source: site module ${INSTRUMENTATION_MODULE}`);
290
+ return policy.pushErrorPageView;
291
+ }
292
+ /**
293
+ * D-16 prepare-phase artifact: serializes BOTH kinds' instrumentation tags
294
+ * (tenant module when present, SDK default otherwise) into
295
+ * error-pages/instrumentation.json under the compiled content root. The
296
+ * AWS-lane code capsule packs source/.aci/compiled/**, so the Go publish
297
+ * materializer reads this file from the capsule and stamps the kind-matching
298
+ * tag into the CDN error artifacts — the tag crosses the JS→Go boundary as
299
+ * data. Serialization failures (bind/method-shorthand exports, FIND-006)
300
+ * throw before anything is written.
301
+ *
302
+ * Exported for unit tests; `content` and `outRoot` are injected there like
303
+ * resolveInstrumentationTag's `content`.
304
+ */
305
+ export async function writeInstrumentationArtifact(root = siteRoot, content, outRoot = contentRoot) {
306
+ const sdk = content ?? (await sdkContent());
307
+ const push = await resolveInstrumentationPush(root);
308
+ const tagFor = (kind) => (push
309
+ ? sdk.serializeErrorPageInstrumentation(push, kind)
310
+ : sdk.errorPageInstrumentationTag(kind));
311
+ const artifact = {
312
+ version: 1,
313
+ notFound: tagFor('notFound'),
314
+ error: tagFor('catchAll'),
315
+ };
316
+ const dir = path.join(outRoot, 'error-pages');
317
+ fs.mkdirSync(dir, { recursive: true });
318
+ const target = path.join(dir, 'instrumentation.json');
319
+ fs.writeFileSync(target, `${JSON.stringify(artifact)}\n`);
320
+ log(`wrote ${path.relative(root, target) || target} (D-16 instrumentation transport)`);
321
+ return target;
322
+ }
323
+ /**
324
+ * Appends the D-14 instrumentation script tag and the generation marker
325
+ * before </body>. Exported for unit tests (the tag is a parameter so the
326
+ * function stays synchronous and dist-free there). Throws when the document
327
+ * has no </body> (quorum BUG-003): writing an UNMARKED 500.html would poison
328
+ * every later build via the skip-if-present contract, so the emit fails
329
+ * loudly instead.
330
+ */
331
+ export function stampInstrumentation(html, instrumentationTag) {
332
+ const stamped = html.replace(/<\/body>/i, `${instrumentationTag}\n${MARKER}\n</body>`);
333
+ if (!stamped.includes(MARKER)) {
334
+ throw new Error('rendered HTML has no </body> tag, so the instrumentation script and generation marker '
335
+ + 'could not be appended; refusing to write an unmarked public/500.html (skip-if-present contract)');
336
+ }
337
+ return stamped;
338
+ }
339
+ function postProcess(html, instrumentationTag) {
340
+ let out = html;
341
+ // Strip every script tag: framework runtime chunks are dead weight in a
342
+ // statically served copy, and this removes the collect script and the
343
+ // data-aci-assignments tag (REQ-11) in one sweep.
344
+ out = out.replace(/<script\b[\s\S]*?<\/script>/gi, '');
345
+ out = out.replace(/<link\b[^>]*rel="(?:preload|modulepreload|prefetch)"[^>]*>/gi, '');
346
+ out = out.replace(/<meta\b[^>]*name="aci-render-proof"[^>]*>/gi, '');
347
+ out = inlineStylesheets(out);
348
+ return stampInstrumentation(out, instrumentationTag);
349
+ }
350
+ async function emit() {
351
+ const publicDir = path.join(siteRoot, 'public');
352
+ const target = path.join(publicDir, '500.html');
353
+ if (fs.existsSync(target) && !fs.readFileSync(target, 'utf8').includes(MARKER)) {
354
+ log('public/500.html already provided by the site; leaving it untouched (skip-if-present)');
355
+ return;
356
+ }
357
+ const { route, defaultHtml } = await resolveCatchAllRoute();
358
+ let instrumentationTag;
359
+ try {
360
+ instrumentationTag = await resolveInstrumentationTag();
361
+ }
362
+ catch (error) {
363
+ fail(error.message);
364
+ }
365
+ let html;
366
+ try {
367
+ if (!route) {
368
+ // The shipped default is already self-contained; it gets the same
369
+ // instrumentation-plus-marker append used for rendered pages.
370
+ html = stampInstrumentation(defaultHtml, instrumentationTag);
371
+ }
372
+ else {
373
+ log(`rendering bound catchAll page ${route} for public/500.html`);
374
+ html = postProcess(await fetchRenderedRoute(route), instrumentationTag);
375
+ }
376
+ }
377
+ catch (error) {
378
+ fail(error.message);
379
+ }
380
+ const size = Buffer.byteLength(html);
381
+ if (size > SIZE_BUDGET) {
382
+ fail(`public/500.html is ${size} bytes, over the ${SIZE_BUDGET}-byte budget (REQ-14). `
383
+ + 'Trim the bound page/design-system CSS or fall back to system fonts (the sanctioned escape hatch).');
384
+ }
385
+ fs.mkdirSync(publicDir, { recursive: true });
386
+ fs.writeFileSync(target, html);
387
+ log(`wrote public/500.html (${size} bytes${route ? `, from ${route}` : ', shipped default'})`);
388
+ }
389
+ // Run only when executed as a CLI — the module is also imported by unit
390
+ // tests for stampInstrumentation.
391
+ const isMain = process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href;
392
+ if (isMain) {
393
+ const phase = process.argv[2];
394
+ if (phase !== 'prepare' && phase !== 'emit') {
395
+ console.error('usage: emit-error-pages.mjs <prepare|emit>');
396
+ process.exit(2);
397
+ }
398
+ if (phase === 'prepare')
399
+ await prepare();
400
+ else
401
+ await emit();
402
+ }