create-foliwake 0.0.0-stage → 0.3.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 (68) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/LICENSE +202 -0
  3. package/README.md +60 -2
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +16 -0
  6. package/dist/cli.d.ts +8 -0
  7. package/dist/cli.js +88 -0
  8. package/dist/create.d.ts +50 -0
  9. package/dist/create.js +250 -0
  10. package/dist/destination.d.ts +47 -0
  11. package/dist/destination.js +243 -0
  12. package/dist/editor-files.d.ts +6 -0
  13. package/dist/editor-files.js +39 -0
  14. package/dist/files.d.ts +26 -0
  15. package/dist/files.js +94 -0
  16. package/dist/git.d.ts +22 -0
  17. package/dist/git.js +64 -0
  18. package/dist/index.d.ts +5 -0
  19. package/dist/index.js +7 -0
  20. package/dist/install.d.ts +12 -0
  21. package/dist/install.js +18 -0
  22. package/dist/options.d.ts +48 -0
  23. package/dist/options.js +54 -0
  24. package/dist/prompts.d.ts +16 -0
  25. package/dist/prompts.js +67 -0
  26. package/dist/starters.d.ts +20 -0
  27. package/dist/starters.js +61 -0
  28. package/dist/validate.d.ts +3 -0
  29. package/dist/validate.js +12 -0
  30. package/package.json +64 -3
  31. package/starters/examples/components/quiz/quiz.css +33 -0
  32. package/starters/examples/components/quiz/quiz.example.md +29 -0
  33. package/starters/examples/components/quiz/quiz.js +36 -0
  34. package/starters/examples/components/quiz/quiz.json +14 -0
  35. package/starters/examples/components/steps/steps.css +38 -0
  36. package/starters/examples/components/steps/steps.example.md +25 -0
  37. package/starters/examples/components/steps/steps.json +8 -0
  38. package/starters/examples/content/blocks.md +49 -0
  39. package/starters/examples/content/index.md +44 -0
  40. package/starters/minimal/components/note/note.css +15 -0
  41. package/starters/minimal/components/note/note.example.md +23 -0
  42. package/starters/minimal/components/note/note.json +8 -0
  43. package/starters/minimal/content/images/foliwake-logo.png +0 -0
  44. package/starters/minimal/content/index.md +32 -0
  45. package/starters/react/components/poll/poll.css +32 -0
  46. package/starters/react/components/poll/poll.example.md +26 -0
  47. package/starters/react/components/poll/poll.js +35 -0
  48. package/starters/react/components/poll/poll.json +13 -0
  49. package/starters/react/scripts/react-view.js +22 -0
  50. package/starters/shared/README.md +104 -0
  51. package/starters/shared/_github/actions/foliwake-request/action.yml +45 -0
  52. package/starters/shared/_github/scripts/foliwake-report.py +68 -0
  53. package/starters/shared/_github/workflows/branch-preview.yml +104 -0
  54. package/starters/shared/_github/workflows/frontend-checks.yml +28 -0
  55. package/starters/shared/_github/workflows/production.yml +134 -0
  56. package/starters/shared/_gitignore +8 -0
  57. package/starters/shared/jsconfig.json +16 -0
  58. package/starters/shared/scripts/components.js +284 -0
  59. package/starters/shared/site.yaml +2 -0
  60. package/starters/shared/styles/styles.css +106 -0
  61. package/starters/shared/tests/site.test.mjs +21 -0
  62. package/starters/shared/tests/workflows.test.mjs +84 -0
  63. package/starters/storybook/_storybook/main.js +46 -0
  64. package/starters/storybook/_storybook/preview.js +7 -0
  65. package/starters/storybook/_storybook/run.mjs +25 -0
  66. package/starters/storybook/pnpm-workspace.yaml +8 -0
  67. package/vendor/react.LICENSE.txt +21 -0
  68. package/vendor/react.js +32 -0
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env python3
2
+ """Job summary and step outputs for the answer of a Foliwake forced command.
3
+
4
+ Usage: foliwake-report.py <production|rollback|branch-preview> <result.json>
5
+ Outputs (GITHUB_OUTPUT): state (the result or state field), url, revision.
6
+ """
7
+ import json, os, sys
8
+
9
+
10
+ def seconds(ms):
11
+ return f'{ms / 1000:.1f} s' if isinstance(ms, (int, float)) else '?'
12
+
13
+
14
+ def timing_lines(t):
15
+ """Where a deploy's time went (its answer's `timings`): the total, then each step with its store requests."""
16
+ if not isinstance(t, dict) or not isinstance(t.get('steps'), dict):
17
+ return []
18
+ store = t.get('store') if isinstance(t.get('store'), dict) else {}
19
+ per_step = t.get('stepStore') if isinstance(t.get('stepStore'), dict) else {}
20
+ out = [f"- took: `{seconds(t.get('totalMs'))}`; pages built: `{t.get('pagesBuilt')}`; store requests: `{store.get('requests')}`", '',
21
+ '| step | time | store requests |', '| --- | ---: | ---: |']
22
+ for step, ms in t['steps'].items():
23
+ requests = per_step.get(step, {}).get('requests') if isinstance(per_step.get(step), dict) else None
24
+ out.append(f"| {step} | {seconds(ms)} | {'' if requests is None else requests} |")
25
+ return out
26
+
27
+
28
+ kind, path = sys.argv[1], sys.argv[2]
29
+ try:
30
+ r = json.load(open(path))
31
+ except (OSError, ValueError):
32
+ r = {'result': 'failed', 'state': 'failed', 'message': 'no JSON answer from the server'}
33
+
34
+ state = r.get('result') or r.get('state') or 'failed'
35
+ with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
36
+ out.write(f"state={state}\nurl={r.get('url') or ''}\nrevision={r.get('revision') or r.get('mainCommit') or ''}\n")
37
+
38
+ if kind == 'branch-preview':
39
+ lines = [f"### Branch preview: {r.get('branch', '')}", '', f'- state: `{state}`']
40
+ if r.get('url'):
41
+ lines.append(f"- URL: {r['url']} (owner Basic auth)")
42
+ rows = [('build commit', r.get('revision')), ('code release', r.get('codeRelease'))]
43
+ else:
44
+ title = 'Frontend production' if kind == 'production' else 'Frontend rollback'
45
+ refresh = r.get('cacheRefresh') or {}
46
+ rows = [('action', r.get('action')), ('commit', r.get('sourceCommit') or r.get('mainCommit')), ('built commit', r.get('mainCommit')),
47
+ ('code release', r.get('codeRelease')), ('preview release', r.get('previewRelease')), ('release with', r.get('expect')),
48
+ ('live release' if kind == 'production' else 'to', r.get('siteRelease')), ('live before', r.get('previousSiteRelease')), ('result', state),
49
+ ('code release mode', r.get('mode')), ('code', r.get('code')), ('operation', r.get('operation')),
50
+ ('cache refresh', refresh.get('state')), ('delivered', r.get('delivered') if kind == 'rollback' or state == 'released' else None), ('record', r.get('record'))]
51
+ lines = [f'### {title}', '']
52
+ if state == 'released':
53
+ rows.append(('next', 'nothing: code and pages are live as one site release; roll back with a manual run of this workflow if needed'))
54
+ elif state == 'prepared' and r.get('held'):
55
+ rows.append(('next', 'the automatic release was held (see the checks below); live is unchanged. Fix it and push again, or review and Release in the Foliwake admin'))
56
+ elif state == 'prepared':
57
+ rows.append(('next', 'review the preview, then Release in the Foliwake admin; live is unchanged'))
58
+ lines += [f'- {k}: `{v}`' for k, v in rows if v is not None]
59
+ lines += timing_lines(r.get('timings'))
60
+ for g in (r.get('gates') or []):
61
+ if isinstance(g, dict):
62
+ lines.append(f" - check {g.get('gate')}: {'ok' if g.get('ok') else 'FAILED'} — {g.get('detail')}")
63
+ for d in (r.get('diagnostics') or [])[:20]:
64
+ lines.append(f" - {d.get('file')}:{d.get('line')} {d.get('code')}: {d.get('message')}")
65
+ if r.get('message'):
66
+ lines.append(f"- {r['message']}")
67
+ with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as summary:
68
+ summary.write('\n'.join(lines) + '\n')
@@ -0,0 +1,104 @@
1
+ # Hosted branch previews: every push to a branch other than main asks the
2
+ # Foliwake server to show exactly that commit as the branch preview
3
+ # https://<branch>--<site>[--<org>].<branch host domain>/: the branch's code over
4
+ # the site's saved preview content (the pages are not rebuilt against the
5
+ # branch's code). Deleting the branch disables its preview. Live and the
6
+ # site's preview are never touched; main is handled by production.yml with
7
+ # another key. This site has no build step: the server takes the code
8
+ # (components/, scripts/, styles/, site.yaml) from the pushed commit itself.
9
+ #
10
+ # INERT until enabled: every job is skipped unless the repository variable
11
+ # BRANCH_PREVIEWS_ENABLED is `true` and FOLIWAKE_SITE_ID is set. How to enable
12
+ # it: README.md, "Connect to a Foliwake server".
13
+ #
14
+ # Credentials (environment `branch-previews`, secret NAMES only):
15
+ # BRANCH_PREVIEW_SSH_KEY, BRANCH_PREVIEW_KNOWN_HOSTS, BRANCH_PREVIEW_SSH_TARGET.
16
+ # The key is restricted on the server to the branch-preview forced command
17
+ # (update/delete one site's branch previews; it cannot release or roll back).
18
+ # Pushes of forks never run here; pull requests are not a trigger.
19
+ #
20
+ # Ordering: cancelling an older run is only an optimisation. The server checks
21
+ # that the commit is still the branch tip, and the engine checks the run
22
+ # sequence (github.run_id), so a delayed older run never replaces a newer one.
23
+ name: Branch preview
24
+ on:
25
+ push:
26
+ branches-ignore: [main]
27
+ delete:
28
+ permissions:
29
+ contents: read
30
+ concurrency:
31
+ group: branch-preview-${{ github.event_name == 'delete' && github.event.ref || github.ref_name }}
32
+ cancel-in-progress: true
33
+ jobs:
34
+ preview:
35
+ if: >-
36
+ vars.BRANCH_PREVIEWS_ENABLED == 'true' &&
37
+ vars.FOLIWAKE_SITE_ID != '' &&
38
+ !github.event.repository.fork &&
39
+ github.event_name == 'push' && !github.event.deleted && github.ref_type == 'branch' &&
40
+ github.ref_name != 'main'
41
+ environment: branch-previews
42
+ runs-on: ubuntu-24.04
43
+ timeout-minutes: 15
44
+ steps:
45
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
46
+ with:
47
+ persist-credentials: false
48
+ - name: Build the request
49
+ env:
50
+ BRANCH: ${{ github.ref_name }}
51
+ SHA: ${{ github.sha }}
52
+ RUN_ID: ${{ github.run_id }}
53
+ SITE: ${{ vars.FOLIWAKE_SITE_ID }}
54
+ run: |
55
+ python3 -c 'import json, os; print(json.dumps({"action": "update", "branch": os.environ["BRANCH"], "revision": os.environ["SHA"], "sequence": int(os.environ["RUN_ID"]), "site": os.environ["SITE"]}))' > "$RUNNER_TEMP/request.json"
56
+ - id: send
57
+ uses: ./.github/actions/foliwake-request
58
+ with:
59
+ command: branch-preview
60
+ request: ${{ runner.temp }}/request.json
61
+ ssh-key: ${{ secrets.BRANCH_PREVIEW_SSH_KEY }}
62
+ known-hosts: ${{ secrets.BRANCH_PREVIEW_KNOWN_HOSTS }}
63
+ target: ${{ secrets.BRANCH_PREVIEW_SSH_TARGET }}
64
+ - name: Report
65
+ env:
66
+ EXIT: ${{ steps.send.outputs.exit }}
67
+ run: |
68
+ python3 .github/scripts/foliwake-report.py branch-preview "$RUNNER_TEMP/foliwake-result.json"
69
+ test "$EXIT" = 0
70
+ delete:
71
+ if: >-
72
+ vars.BRANCH_PREVIEWS_ENABLED == 'true' &&
73
+ vars.FOLIWAKE_SITE_ID != '' &&
74
+ !github.event.repository.fork &&
75
+ github.event_name == 'delete' && github.event.ref_type == 'branch' &&
76
+ github.event.ref != 'main'
77
+ environment: branch-previews
78
+ runs-on: ubuntu-24.04
79
+ timeout-minutes: 15
80
+ steps:
81
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
82
+ with:
83
+ persist-credentials: false
84
+ - name: Build the request
85
+ env:
86
+ BRANCH: ${{ github.event.ref }}
87
+ RUN_ID: ${{ github.run_id }}
88
+ SITE: ${{ vars.FOLIWAKE_SITE_ID }}
89
+ run: |
90
+ python3 -c 'import json, os; print(json.dumps({"action": "delete", "branch": os.environ["BRANCH"], "sequence": int(os.environ["RUN_ID"]), "site": os.environ["SITE"]}))' > "$RUNNER_TEMP/request.json"
91
+ - id: send
92
+ uses: ./.github/actions/foliwake-request
93
+ with:
94
+ command: branch-preview
95
+ request: ${{ runner.temp }}/request.json
96
+ ssh-key: ${{ secrets.BRANCH_PREVIEW_SSH_KEY }}
97
+ known-hosts: ${{ secrets.BRANCH_PREVIEW_KNOWN_HOSTS }}
98
+ target: ${{ secrets.BRANCH_PREVIEW_SSH_TARGET }}
99
+ - name: Report
100
+ env:
101
+ EXIT: ${{ steps.send.outputs.exit }}
102
+ run: |
103
+ python3 .github/scripts/foliwake-report.py branch-preview "$RUNNER_TEMP/foliwake-result.json"
104
+ test "$EXIT" = 0
@@ -0,0 +1,28 @@
1
+ # Frontend checks: the required status check for pull requests into main, and
2
+ # the gate of the production workflow (production.yml calls this workflow).
3
+ # No secrets, read-only token, nothing installed in the project: @foliwake/site-check runs with npx at the
4
+ # version the project was created with. Safe for fork pull requests.
5
+ name: Frontend checks
6
+ on:
7
+ pull_request:
8
+ push:
9
+ branches-ignore: [main] # main runs these checks inside production.yml
10
+ workflow_call:
11
+ permissions:
12
+ contents: read
13
+ jobs:
14
+ test:
15
+ name: frontend-checks
16
+ runs-on: ubuntu-24.04
17
+ timeout-minutes: 10
18
+ steps:
19
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
20
+ with:
21
+ persist-credentials: false
22
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
23
+ with:
24
+ node-version: '22'
25
+ - name: Site code (the platform's own checks)
26
+ run: npx -y @foliwake/site-check@{{siteCheckVersion}} . --format github
27
+ - name: Tests (vendored scripts, workflow guards)
28
+ run: node --test "tests/*.test.mjs"
@@ -0,0 +1,134 @@
1
+ # Frontend production: a push to main (normally a merged pull request) runs the
2
+ # frontend checks and asks the Foliwake server to deploy exactly that commit:
3
+ # the server makes a code release from it and rebuilds every page against it
4
+ # in the site's preview. With the site setting `codeRelease: auto` (the
5
+ # default) the server then checks the rebuild (every page built, no page with
6
+ # problems, the code fits the pages) and releases code and pages to live as one
7
+ # site release: merge to main = release. If a check fails, or the site uses
8
+ # `codeRelease: manual`, the code waits in the preview and you release it in
9
+ # the Foliwake admin (Frontend > New code > Release); live is unchanged.
10
+ # This site has no build step: the server takes the code from the main commit.
11
+ # Manual rollback (workflow_dispatch) makes an earlier site release live again,
12
+ # only while live is still the release you name as `expect`.
13
+ #
14
+ # Ordering: one run at a time (concurrency). The server refuses a commit that
15
+ # is no longer the tip of main and a deploy older than one it already prepared.
16
+ #
17
+ # INERT until enabled: the deploy and rollback jobs are skipped unless the
18
+ # repository variable FRONTEND_PRODUCTION_DEPLOY_ENABLED is `true` (separate
19
+ # from BRANCH_PREVIEWS_ENABLED) and FOLIWAKE_SITE_ID is set. How to enable it:
20
+ # README.md, "Connect to a Foliwake server".
21
+ #
22
+ # Credentials (environment `production`, deployment branches: main only,
23
+ # secret NAMES only): PRODUCTION_DEPLOY_SSH_KEY, PRODUCTION_DEPLOY_KNOWN_HOSTS,
24
+ # PRODUCTION_DEPLOY_SSH_TARGET. The key can deploy main (and so release it when the
25
+ # site's checks pass) and roll back; it cannot release any other preview.
26
+ name: Frontend production
27
+ on:
28
+ push:
29
+ branches: [main]
30
+ workflow_dispatch:
31
+ inputs:
32
+ to:
33
+ description: 'Rollback target: "previous" (one site release back from live) or a site release sr_…'
34
+ required: true
35
+ default: previous
36
+ type: string
37
+ expect:
38
+ description: 'The live site release you saw (sr_…, from the Foliwake admin or `site status`); nothing changes if live is no longer it'
39
+ required: true
40
+ type: string
41
+ permissions:
42
+ contents: read
43
+ concurrency:
44
+ # One production operation at a time; a running one is never cancelled.
45
+ group: frontend-production
46
+ cancel-in-progress: false
47
+ jobs:
48
+ checks:
49
+ if: github.event_name == 'push'
50
+ uses: ./.github/workflows/frontend-checks.yml
51
+ deploy:
52
+ needs: checks
53
+ if: >-
54
+ github.event_name == 'push' &&
55
+ github.ref == 'refs/heads/main' &&
56
+ vars.FRONTEND_PRODUCTION_DEPLOY_ENABLED == 'true' &&
57
+ vars.FOLIWAKE_SITE_ID != '' &&
58
+ !github.event.repository.fork
59
+ environment:
60
+ name: production
61
+ url: ${{ vars.FOLIWAKE_PRODUCTION_URL }}
62
+ runs-on: ubuntu-24.04
63
+ timeout-minutes: 30
64
+ steps:
65
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
66
+ with:
67
+ persist-credentials: false
68
+ - name: Build the request
69
+ env:
70
+ SHA: ${{ github.sha }}
71
+ RUN_ID: ${{ github.run_id }}
72
+ SITE: ${{ vars.FOLIWAKE_SITE_ID }}
73
+ run: |
74
+ python3 -c 'import json, os; print(json.dumps({"action": "deploy", "revision": os.environ["SHA"], "sequence": int(os.environ["RUN_ID"]), "site": os.environ["SITE"]}))' > "$RUNNER_TEMP/request.json"
75
+ - id: send
76
+ uses: ./.github/actions/foliwake-request
77
+ with:
78
+ command: frontend-production
79
+ request: ${{ runner.temp }}/request.json
80
+ ssh-key: ${{ secrets.PRODUCTION_DEPLOY_SSH_KEY }}
81
+ known-hosts: ${{ secrets.PRODUCTION_DEPLOY_KNOWN_HOSTS }}
82
+ target: ${{ secrets.PRODUCTION_DEPLOY_SSH_TARGET }}
83
+ - name: Report (fails unless released, prepared for a manual release, or superseded)
84
+ env:
85
+ EXIT: ${{ steps.send.outputs.exit }}
86
+ run: |
87
+ python3 .github/scripts/foliwake-report.py production "$RUNNER_TEMP/foliwake-result.json"
88
+ # 0: released (delivered), prepared (codeRelease: manual) or superseded; 3: released, cache
89
+ # refresh still pending; 1: failed, refused, or held by a check (the code waits in preview).
90
+ test "$EXIT" = 0
91
+ rollback:
92
+ if: >-
93
+ github.event_name == 'workflow_dispatch' &&
94
+ github.ref == 'refs/heads/main' &&
95
+ vars.FRONTEND_PRODUCTION_DEPLOY_ENABLED == 'true' &&
96
+ vars.FOLIWAKE_SITE_ID != '' &&
97
+ !github.event.repository.fork
98
+ environment:
99
+ name: production
100
+ url: ${{ vars.FOLIWAKE_PRODUCTION_URL }}
101
+ runs-on: ubuntu-24.04
102
+ timeout-minutes: 20
103
+ steps:
104
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
105
+ with:
106
+ persist-credentials: false
107
+ - name: Build the request (site releases only, with the live release you saw)
108
+ env:
109
+ TO: ${{ inputs.to }}
110
+ EXPECT: ${{ inputs.expect }}
111
+ SITE: ${{ vars.FOLIWAKE_SITE_ID }}
112
+ run: |
113
+ python3 - <<'PY' > "$RUNNER_TEMP/request.json"
114
+ import json, os, re, sys
115
+ to, expect = os.environ['TO'], os.environ['EXPECT']
116
+ if not (to == 'previous' or re.fullmatch(r'sr_[0-9a-f]{32}', to)) or not re.fullmatch(r'sr_[0-9a-f]{32}', expect):
117
+ sys.exit('to must be "previous" or sr_…, and expect the live sr_… you saw')
118
+ print(json.dumps({'action': 'rollback', 'to': to, 'expect': expect, 'site': os.environ['SITE']}))
119
+ PY
120
+ - id: send
121
+ uses: ./.github/actions/foliwake-request
122
+ with:
123
+ command: frontend-production
124
+ request: ${{ runner.temp }}/request.json
125
+ ssh-key: ${{ secrets.PRODUCTION_DEPLOY_SSH_KEY }}
126
+ known-hosts: ${{ secrets.PRODUCTION_DEPLOY_KNOWN_HOSTS }}
127
+ target: ${{ secrets.PRODUCTION_DEPLOY_SSH_TARGET }}
128
+ - name: Report (fails unless delivered or a no-op)
129
+ env:
130
+ EXIT: ${{ steps.send.outputs.exit }}
131
+ run: |
132
+ python3 .github/scripts/foliwake-report.py rollback "$RUNNER_TEMP/foliwake-result.json"
133
+ # 0: delivered / noop; 3: committed but the cache refresh is still pending; 1: refused or failed.
134
+ test "$EXIT" = 0
@@ -0,0 +1,8 @@
1
+ # Local Foliwake state of `foliwake dev` and other local commands
2
+ .foliwake/
3
+ node_modules/
4
+ storybook-static/
5
+ .DS_Store
6
+ # Environment files hold secrets; never commit them
7
+ .env
8
+ .env.*
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "allowJs": true,
7
+ "checkJs": false,
8
+ "noEmit": true,
9
+ "paths": {
10
+ "@foliwake/block-kit": ["./.foliwake/types/foliwake.d.ts"],
11
+ "foliwake": ["./.foliwake/types/foliwake.d.ts"]
12
+ }
13
+ },
14
+ "include": ["components/**/*.js", "scripts/**/*.js", "templates/**/*.js", ".foliwake/types/**/*.d.ts"],
15
+ "exclude": ["scripts/vendor/**"]
16
+ }
@@ -0,0 +1,284 @@
1
+ // Component loader (content-components.md §8.3, HTML contract 1).
2
+ //
3
+ // Finds every [data-component] root, loads only the assets that
4
+ // components/components.json declares, calls each module's default
5
+ // `init(root, host, meta)` once per root (`meta`: the block's name and its `ui`
6
+ // labels from the descriptor) and marks the root with
7
+ // data-component-status="loading" | "ready" | "error". A component stylesheet
8
+ // the page shell already links (link[data-component-css="<name>"]) is reused
9
+ // when its outcome is known (see shellCss), not added again.
10
+ //
11
+ // Failure codes (logged as console.error('[components]', code, name, root, error)):
12
+ // LOADER_DESCRIPTOR_FAILED components.json could not be fetched or is not a valid descriptor
13
+ // LOADER_CONTRACT_MISMATCH descriptor htmlContract differs from <html data-html-contract>
14
+ // LOADER_UNKNOWN_COMPONENT the root's name is not declared in the descriptor
15
+ // LOADER_CSS_FAILED the component stylesheet failed (`error` event, or a failed request of a shell link)
16
+ // LOADER_JS_FAILED import() of the component module rejected (404, syntax error, ...)
17
+ // LOADER_INIT_INVALID the module has no default export function
18
+ // LOADER_BLOCK_NAME_MISMATCH the module's defineBlock('<name>', …) names another block than its folder
19
+ // LOADER_BLOCK_CONTRACT the module declares another major of the blocks contract (`init.contract`)
20
+ // LOADER_INIT_FAILED init(root, host) threw synchronously or returned a rejected Promise
21
+ //
22
+ // `host` is the page's BlockHost (blocks contract foliwake-blocks/2 §2, @foliwake/blocks-contract):
23
+ // the core one of a Foliwake page, the same object for every block. Inside a React or Next app
24
+ // (@foliwake/react) the same blocks get the app's host instead (its labels, `host.react`, an extension's
25
+ // members, …), so a block that reads only what this host has works in both. Optional members (`mode`,
26
+ // `media`, `track`, `labels`, `react`, any extension's) are absent here: `has(name)` says so, and a block
27
+ // falls back.
28
+ //
29
+ // In <html data-env="local|preview"> each failed root also gets a visible
30
+ // notice immediately before it. In "live" failures go to the console only.
31
+ // The loader never removes or hides authored content and exports nothing.
32
+
33
+ const codeBase = new URL('../', import.meta.url);
34
+ const descriptorUrl = new URL('components/components.json', codeBase);
35
+ const NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
36
+
37
+ /** The major of the blocks contract this loader speaks; a block that declares another one is refused. */
38
+ const BLOCKS_CONTRACT_MAJOR = 2;
39
+
40
+ const html = document.documentElement;
41
+ const prefers = (query) => typeof matchMedia === 'function' && matchMedia(query).matches;
42
+ const theme = html.dataset.theme === 'dark' || html.dataset.theme === 'light' ? html.dataset.theme : prefers('(prefers-color-scheme: dark)') ? 'dark' : 'light';
43
+ const host = Object.freeze({
44
+ contract: Object.freeze({ major: BLOCKS_CONTRACT_MAJOR, minor: 0 }),
45
+ shell: 'foliwake',
46
+ htmlContract: html.dataset.htmlContract ?? '',
47
+ channel: html.dataset.env === 'live' ? 'live' : 'preview',
48
+ env: html.dataset.env,
49
+ lang: html.lang || 'en',
50
+ uiLang: html.lang || 'en',
51
+ theme,
52
+ reducedMotion: prefers('(prefers-reduced-motion: reduce)'),
53
+ signal: new AbortController().signal, // a page never disposes its blocks
54
+ keyOf: (root) => root.getAttribute('data-block-key') ?? '',
55
+ has: (feature) => feature === 'signal' || feature === 'channel',
56
+ });
57
+
58
+ const initialized = new WeakSet();
59
+ const cssPromises = new Map();
60
+ const modulePromises = new Map();
61
+
62
+ function assetUrl(name, ext) {
63
+ return new URL(`components/${name}/${name}.${ext}`, codeBase);
64
+ }
65
+
66
+ function showNotices() {
67
+ const env = document.documentElement.dataset.env;
68
+ return env === 'local' || env === 'preview';
69
+ }
70
+
71
+ function fail(root, name, code, error) {
72
+ console.error('[components]', code, name, root, error);
73
+ root.setAttribute('data-component-status', 'error');
74
+ if (!showNotices()) return;
75
+ const previous = root.previousElementSibling;
76
+ if (previous && previous.matches('p[data-component-error]')) return; // one notice per root
77
+ const notice = document.createElement('p');
78
+ notice.className = 'component-error';
79
+ notice.setAttribute('role', 'alert');
80
+ notice.setAttribute('data-component-error', name);
81
+ notice.style.outline = '2px solid #b00020';
82
+ notice.style.outlineOffset = '2px';
83
+ notice.textContent = `Component "${name}" failed (${code}). See the browser console.`;
84
+ root.before(notice);
85
+ }
86
+
87
+ class LoaderError extends Error {
88
+ constructor(code, message, cause) {
89
+ super(message, cause === undefined ? undefined : { cause });
90
+ this.code = code;
91
+ }
92
+ }
93
+
94
+ // The outcome of a stylesheet request from its resource timing entry: true
95
+ // (2xx), false (4xx/5xx) or null when it cannot be known (no entry yet, timings
96
+ // cleared or the buffer full, no responseStatus support, or status 0: a
97
+ // network error and a hidden cross-origin status, also after a same-origin URL
98
+ // redirects elsewhere, look the same). The sheet is never used: Chrome gives a
99
+ // failed link an empty sheet too.
100
+ function timingOutcome(href) {
101
+ const entry = performance.getEntriesByName(href, 'resource').at(-1);
102
+ const status = entry?.responseStatus;
103
+ if (typeof status !== 'number' || status === 0) return null;
104
+ return status >= 200 && status < 300;
105
+ }
106
+
107
+ // Component stylesheets the page shell links, with their outcome taken when
108
+ // the loader starts: the shell links come before this module script, so the
109
+ // browser has finished them, and the timing entries are read before anything
110
+ // else on the page can clear them. Outcome null (not known) means the loader
111
+ // adds a fresh link for that component and tracks it itself (one more request)
112
+ // rather than guessing.
113
+ const shellCss = new Map(); // name -> true | false | null
114
+ for (const link of document.querySelectorAll('link[rel="stylesheet"][data-component-css]')) {
115
+ const name = link.getAttribute('data-component-css');
116
+ if (!shellCss.has(name)) shellCss.set(name, timingOutcome(link.href));
117
+ }
118
+
119
+ function addCss(name) {
120
+ return new Promise((resolve, reject) => {
121
+ const link = document.createElement('link');
122
+ link.rel = 'stylesheet';
123
+ link.setAttribute('data-component-css', name);
124
+ link.addEventListener('load', () => resolve(), { once: true });
125
+ link.addEventListener('error', () => {
126
+ reject(new LoaderError('LOADER_CSS_FAILED', `Stylesheet for "${name}" failed to load.`));
127
+ }, { once: true });
128
+ link.href = assetUrl(name, 'css').href;
129
+ document.head.append(link);
130
+ });
131
+ }
132
+
133
+ function loadCss(name) {
134
+ if (!cssPromises.has(name)) {
135
+ const known = shellCss.get(name);
136
+ const promise = known === true
137
+ ? Promise.resolve()
138
+ : known === false
139
+ ? Promise.reject(new LoaderError('LOADER_CSS_FAILED', `Stylesheet for "${name}" failed to load.`))
140
+ : addCss(name);
141
+ promise.catch(() => {}); // handled per root
142
+ cssPromises.set(name, promise);
143
+ }
144
+ return cssPromises.get(name);
145
+ }
146
+
147
+ function loadModule(name) {
148
+ if (!modulePromises.has(name)) {
149
+ const promise = import(assetUrl(name, 'js').href).then(
150
+ (module) => {
151
+ if (typeof module.default !== 'function') {
152
+ throw new LoaderError('LOADER_INIT_INVALID', `Module for "${name}" has no default export function.`);
153
+ }
154
+ // block-kit's init carries the name given to defineBlock; a hand-written init has none.
155
+ const declared = module.default.block;
156
+ if (typeof declared === 'string' && declared !== name) {
157
+ throw new LoaderError('LOADER_BLOCK_NAME_MISMATCH', `Module for "${name}" defines the block "${declared}".`);
158
+ }
159
+ // A declared contract major (block-kit sets it) must be this loader's; none declared is accepted.
160
+ const contract = module.default.contract;
161
+ if (contract !== undefined && contract !== BLOCKS_CONTRACT_MAJOR) {
162
+ const speaks = `foliwake-blocks/${contract}`;
163
+ const expected = `foliwake-blocks/${BLOCKS_CONTRACT_MAJOR}`;
164
+ throw new LoaderError('LOADER_BLOCK_CONTRACT', `Module for "${name}" speaks ${speaks}; this page loads ${expected}.`);
165
+ }
166
+ return module.default;
167
+ },
168
+ (error) => {
169
+ throw new LoaderError('LOADER_JS_FAILED', `Module for "${name}" failed to load.`, error);
170
+ },
171
+ );
172
+ promise.catch(() => {});
173
+ modulePromises.set(name, promise);
174
+ }
175
+ return modulePromises.get(name);
176
+ }
177
+
178
+ async function fetchDescriptor() {
179
+ let descriptor;
180
+ try {
181
+ const response = await fetch(descriptorUrl);
182
+ if (!response.ok) {
183
+ response.body?.cancel().catch(() => {});
184
+ throw new Error(`HTTP ${response.status}`);
185
+ }
186
+ descriptor = await response.json();
187
+ } catch (error) {
188
+ throw new LoaderError('LOADER_DESCRIPTOR_FAILED', 'Component descriptor could not be loaded.', error);
189
+ }
190
+ const valid = descriptor !== null && typeof descriptor === 'object'
191
+ && descriptor.components !== null && typeof descriptor.components === 'object'
192
+ && !Array.isArray(descriptor.components);
193
+ if (!valid) {
194
+ throw new LoaderError('LOADER_DESCRIPTOR_FAILED', 'Component descriptor is not valid.');
195
+ }
196
+ if (String(descriptor.htmlContract) !== document.documentElement.dataset.htmlContract) {
197
+ throw new LoaderError(
198
+ 'LOADER_CONTRACT_MISMATCH',
199
+ `Descriptor htmlContract ${descriptor.htmlContract} does not match page contract ${document.documentElement.dataset.htmlContract}.`,
200
+ );
201
+ }
202
+ return descriptor;
203
+ }
204
+
205
+ // What the block learns about itself from the descriptor (blocks contract BlockMeta).
206
+ function metaOf(name, entry) {
207
+ const ui = entry.ui !== null && typeof entry.ui === 'object' && !Array.isArray(entry.ui) ? entry.ui : undefined;
208
+ return Object.freeze(ui ? { name, ui } : { name });
209
+ }
210
+
211
+ function errorCode(error) {
212
+ return error instanceof LoaderError ? error.code : 'LOADER_INIT_FAILED';
213
+ }
214
+
215
+ // One root: init (if JS) and CSS are tracked independently; the root is
216
+ // "ready" only when both succeeded, "error" as soon as either fails.
217
+ async function processRoot(root, name, entry) {
218
+ const css = entry.css === true ? loadCss(name) : Promise.resolve();
219
+ const js = entry.js === true
220
+ ? loadModule(name).then((init) => Promise.resolve().then(() => init(root, host, metaOf(name, entry))).catch((error) => {
221
+ throw error instanceof LoaderError ? error : new LoaderError('LOADER_INIT_FAILED', `init failed for "${name}".`, error);
222
+ }))
223
+ : Promise.resolve();
224
+
225
+ let failed = false;
226
+ const report = (error) => {
227
+ failed = true;
228
+ fail(root, name, errorCode(error), error instanceof LoaderError && error.cause !== undefined ? error.cause : error);
229
+ };
230
+ await Promise.allSettled([css.catch(report), js.catch(report)]);
231
+ if (!failed) root.setAttribute('data-component-status', 'ready');
232
+ }
233
+
234
+ function collectRoots() {
235
+ const roots = [];
236
+ for (const root of document.querySelectorAll('[data-component]')) {
237
+ if (initialized.has(root) || root.hasAttribute('data-component-status')) continue;
238
+ initialized.add(root);
239
+ root.setAttribute('data-component-status', 'loading');
240
+ roots.push(root);
241
+ }
242
+ return roots;
243
+ }
244
+
245
+ async function run() {
246
+ // Collect and mark synchronously, so a second copy of the loader (even at a
247
+ // different URL) sees the status attribute and skips these roots.
248
+ const roots = collectRoots();
249
+ if (roots.length === 0) return;
250
+
251
+ let descriptor;
252
+ try {
253
+ descriptor = await fetchDescriptor();
254
+ } catch (error) {
255
+ for (const root of roots) fail(root, root.dataset.component, error.code, error.cause ?? error);
256
+ return;
257
+ }
258
+
259
+ const byName = new Map();
260
+ for (const root of roots) {
261
+ const name = root.dataset.component;
262
+ if (!byName.has(name)) byName.set(name, []);
263
+ byName.get(name).push(root);
264
+ }
265
+
266
+ const work = [];
267
+ for (const [name, nameRoots] of byName) {
268
+ const declared = NAME_PATTERN.test(name) && Object.hasOwn(descriptor.components, name);
269
+ const entry = declared ? descriptor.components[name] : null;
270
+ if (!entry || typeof entry !== 'object') {
271
+ const error = new LoaderError('LOADER_UNKNOWN_COMPONENT', `Component "${name}" is not declared in components.json.`);
272
+ for (const root of nameRoots) fail(root, name, error.code, error);
273
+ continue;
274
+ }
275
+ for (const root of nameRoots) work.push(processRoot(root, name, entry));
276
+ }
277
+ await Promise.allSettled(work);
278
+ }
279
+
280
+ if (document.readyState === 'loading') {
281
+ document.addEventListener('DOMContentLoaded', () => { run(); }, { once: true });
282
+ } else {
283
+ run();
284
+ }
@@ -0,0 +1,2 @@
1
+ version: 1
2
+ authoring: blocks-v3