@vibes.diy/api-queue 0.0.0-smoke-70d942c5-1774564519
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +232 -0
- package/README.md +539 -0
- package/package.json +25 -0
- package/screen-shotter.d.ts +3 -0
- package/screen-shotter.js +70 -0
- package/screen-shotter.js.map +1 -0
- package/tsconfig.json +19 -0
- package/worker.d.ts +6 -0
- package/worker.js +22 -0
- package/worker.js.map +1 -0
- package/wrangler.toml +61 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
The contents of this repository are Copyright (c) corresponding authors and
|
|
2
|
+
contributors, licensed under the `Permissive License Stack` meaning either of:
|
|
3
|
+
|
|
4
|
+
- Apache-2.0 Software License: https://www.apache.org/licenses/LICENSE-2.0
|
|
5
|
+
([...4tr2kfsq](https://dweb.link/ipfs/bafkreiankqxazcae4onkp436wag2lj3ccso4nawxqkkfckd6cg4tr2kfsq))
|
|
6
|
+
|
|
7
|
+
- MIT Software License: https://opensource.org/licenses/MIT
|
|
8
|
+
([...vljevcba](https://dweb.link/ipfs/bafkreiepofszg4gfe2gzuhojmksgemsub2h4uy2gewdnr35kswvljevcba))
|
|
9
|
+
|
|
10
|
+
You may not use the contents of this repository except in compliance
|
|
11
|
+
with one of the listed Licenses. For an extended clarification of the
|
|
12
|
+
intent behind the choice of Licensing please refer to
|
|
13
|
+
https://protocol.ai/blog/announcing-the-permissive-license-stack/
|
|
14
|
+
|
|
15
|
+
Unless required by applicable law or agreed to in writing, software
|
|
16
|
+
distributed under the terms listed in this notice is distributed on
|
|
17
|
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
|
18
|
+
either express or implied. See each License for the specific language
|
|
19
|
+
governing permissions and limitations under that License.
|
|
20
|
+
|
|
21
|
+
<!--- SPDX-License-Identifier: Apache-2.0 OR MIT -->
|
|
22
|
+
|
|
23
|
+
`SPDX-License-Identifier: Apache-2.0 OR MIT`
|
|
24
|
+
|
|
25
|
+
Verbatim copies of both licenses are included below:
|
|
26
|
+
|
|
27
|
+
<details><summary>Apache-2.0 Software License</summary>
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
Apache License
|
|
31
|
+
Version 2.0, January 2004
|
|
32
|
+
http://www.apache.org/licenses/
|
|
33
|
+
|
|
34
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
35
|
+
|
|
36
|
+
1. Definitions.
|
|
37
|
+
|
|
38
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
39
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
40
|
+
|
|
41
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
42
|
+
the copyright owner that is granting the License.
|
|
43
|
+
|
|
44
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
45
|
+
other entities that control, are controlled by, or are under common
|
|
46
|
+
control with that entity. For the purposes of this definition,
|
|
47
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
48
|
+
direction or management of such entity, whether by contract or
|
|
49
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
50
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
51
|
+
|
|
52
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
53
|
+
exercising permissions granted by this License.
|
|
54
|
+
|
|
55
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
56
|
+
including but not limited to software source code, documentation
|
|
57
|
+
source, and configuration files.
|
|
58
|
+
|
|
59
|
+
"Object" form shall mean any form resulting from mechanical
|
|
60
|
+
transformation or translation of a Source form, including but
|
|
61
|
+
not limited to compiled object code, generated documentation,
|
|
62
|
+
and conversions to other media types.
|
|
63
|
+
|
|
64
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
65
|
+
Object form, made available under the License, as indicated by a
|
|
66
|
+
copyright notice that is included in or attached to the work
|
|
67
|
+
(an example is provided in the Appendix below).
|
|
68
|
+
|
|
69
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
70
|
+
form, that is based on (or derived from) the Work and for which the
|
|
71
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
72
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
73
|
+
of this License, Derivative Works shall not include works that remain
|
|
74
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
75
|
+
the Work and Derivative Works thereof.
|
|
76
|
+
|
|
77
|
+
"Contribution" shall mean any work of authorship, including
|
|
78
|
+
the original version of the Work and any modifications or additions
|
|
79
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
80
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
81
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
82
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
83
|
+
means any form of electronic, verbal, or written communication sent
|
|
84
|
+
to the Licensor or its representatives, including but not limited to
|
|
85
|
+
communication on electronic mailing lists, source code control systems,
|
|
86
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
87
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
88
|
+
excluding communication that is conspicuously marked or otherwise
|
|
89
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
90
|
+
|
|
91
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
92
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
93
|
+
subsequently incorporated within the Work.
|
|
94
|
+
|
|
95
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
96
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
97
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
98
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
99
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
100
|
+
Work and such Derivative Works in Source or Object form.
|
|
101
|
+
|
|
102
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
103
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
104
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
105
|
+
(except as stated in this section) patent license to make, have made,
|
|
106
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
107
|
+
where such license applies only to those patent claims licensable
|
|
108
|
+
by such Contributor that are necessarily infringed by their
|
|
109
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
110
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
111
|
+
institute patent litigation against any entity (including a
|
|
112
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
113
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
114
|
+
or contributory patent infringement, then any patent licenses
|
|
115
|
+
granted to You under this License for that Work shall terminate
|
|
116
|
+
as of the date such litigation is filed.
|
|
117
|
+
|
|
118
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
119
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
120
|
+
modifications, and in Source or Object form, provided that You
|
|
121
|
+
meet the following conditions:
|
|
122
|
+
|
|
123
|
+
(a) You must give any other recipients of the Work or
|
|
124
|
+
Derivative Works a copy of this License; and
|
|
125
|
+
|
|
126
|
+
(b) You must cause any modified files to carry prominent notices
|
|
127
|
+
stating that You changed the files; and
|
|
128
|
+
|
|
129
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
130
|
+
that You distribute, all copyright, patent, trademark, and
|
|
131
|
+
attribution notices from the Source form of the Work,
|
|
132
|
+
excluding those notices that do not pertain to any part of
|
|
133
|
+
the Derivative Works; and
|
|
134
|
+
|
|
135
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
136
|
+
distribution, then any Derivative Works that You distribute must
|
|
137
|
+
include a readable copy of the attribution notices contained
|
|
138
|
+
within such NOTICE file, excluding those notices that do not
|
|
139
|
+
pertain to any part of the Derivative Works, in at least one
|
|
140
|
+
of the following places: within a NOTICE text file distributed
|
|
141
|
+
as part of the Derivative Works; within the Source form or
|
|
142
|
+
documentation, if provided along with the Derivative Works; or,
|
|
143
|
+
within a display generated by the Derivative Works, if and
|
|
144
|
+
wherever such third-party notices normally appear. The contents
|
|
145
|
+
of the NOTICE file are for informational purposes only and
|
|
146
|
+
do not modify the License. You may add Your own attribution
|
|
147
|
+
notices within Derivative Works that You distribute, alongside
|
|
148
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
149
|
+
that such additional attribution notices cannot be construed
|
|
150
|
+
as modifying the License.
|
|
151
|
+
|
|
152
|
+
You may add Your own copyright statement to Your modifications and
|
|
153
|
+
may provide additional or different license terms and conditions
|
|
154
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
155
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
156
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
157
|
+
the conditions stated in this License.
|
|
158
|
+
|
|
159
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
160
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
161
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
162
|
+
this License, without any additional terms or conditions.
|
|
163
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
164
|
+
the terms of any separate license agreement you may have executed
|
|
165
|
+
with Licensor regarding such Contributions.
|
|
166
|
+
|
|
167
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
168
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
169
|
+
except as required for reasonable and customary use in describing the
|
|
170
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
171
|
+
|
|
172
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
173
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
174
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
175
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
176
|
+
implied, including, without limitation, any warranties or conditions
|
|
177
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
178
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
179
|
+
appropriateness of using or redistributing the Work and assume any
|
|
180
|
+
risks associated with Your exercise of permissions under this License.
|
|
181
|
+
|
|
182
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
183
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
184
|
+
unless required by applicable law (such as deliberate and grossly
|
|
185
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
186
|
+
liable to You for damages, including any direct, indirect, special,
|
|
187
|
+
incidental, or consequential damages of any character arising as a
|
|
188
|
+
result of this License or out of the use or inability to use the
|
|
189
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
190
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
191
|
+
other commercial damages or losses), even if such Contributor
|
|
192
|
+
has been advised of the possibility of such damages.
|
|
193
|
+
|
|
194
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
195
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
196
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
197
|
+
or other liability obligations and/or rights consistent with this
|
|
198
|
+
License. However, in accepting such obligations, You may act only
|
|
199
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
200
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
201
|
+
defend, and hold each Contributor harmless for any liability
|
|
202
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
203
|
+
of your accepting any such warranty or additional liability.
|
|
204
|
+
|
|
205
|
+
END OF TERMS AND CONDITIONS
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
</details>
|
|
209
|
+
|
|
210
|
+
<details><summary>MIT Software License</summary>
|
|
211
|
+
|
|
212
|
+
```
|
|
213
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
214
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
215
|
+
in the Software without restriction, including without limitation the rights
|
|
216
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
217
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
218
|
+
furnished to do so, subject to the following conditions:
|
|
219
|
+
|
|
220
|
+
The above copyright notice and this permission notice shall be included in
|
|
221
|
+
all copies or substantial portions of the Software.
|
|
222
|
+
|
|
223
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
224
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
225
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
226
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
227
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
228
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
229
|
+
THE SOFTWARE.
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
</details>
|
package/README.md
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
# vibes.diy API
|
|
2
|
+
|
|
3
|
+
WebSocket-based API for vibes.diy chat persistence and app deployment. Supports both HTTP POST and WebSocket connections using the same handler via the Evento event-driven framework.
|
|
4
|
+
|
|
5
|
+
## Package Structure
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
api/
|
|
9
|
+
├── types/ @vibes.diy/api-types SHARED (client + server)
|
|
10
|
+
│ ├── msg-types.ts Request/response types, VibeFile, MsgBase envelope, arktype schemas
|
|
11
|
+
│ ├── types.ts FileSystemItem with transform support
|
|
12
|
+
│ └── vibes-diy-serv-ctx.ts Server context for wrapper/iframe rendering
|
|
13
|
+
│
|
|
14
|
+
├── pkg/ @vibes.diy/api-pkg SHARED (client + server)
|
|
15
|
+
│ ├── api.ts VibesDiyApiIface interface (3 methods)
|
|
16
|
+
│ ├── encoder.ts Evento encoders: ReqRes, W3CWebSocket, Combined
|
|
17
|
+
│ ├── index.ts Re-exports
|
|
18
|
+
│ └── react/ React components (client only in practice)
|
|
19
|
+
│
|
|
20
|
+
├── impl/ @vibes.diy/api-impl CLIENT
|
|
21
|
+
│ └── index.ts VibeDiyApi class (WebSocket client, WIP - no reconnection)
|
|
22
|
+
│
|
|
23
|
+
├── svc/ @vibes.diy/api-svc SERVER (Cloudflare Workers)
|
|
24
|
+
│ ├── cf-serve.ts Cloudflare Worker entry point (HTTP + WebSocket)
|
|
25
|
+
│ ├── create-handler.ts Evento pipeline setup with all handlers
|
|
26
|
+
│ ├── check-auth.ts Auth middleware (clerk, device-id verification)
|
|
27
|
+
│ ├── unwrap-msg-base.ts MsgBase envelope unwrapping for validation
|
|
28
|
+
│ ├── api.ts VibesApiSQLCtx type + VibesFPApiParameters
|
|
29
|
+
│ ├── entry-point-utils.ts URL construction for deployed apps
|
|
30
|
+
│ │
|
|
31
|
+
│ ├── public/ Public API handlers (Evento handlers)
|
|
32
|
+
│ │ ├── ensure-app-slug-item.ts App deployment with CID-based storage
|
|
33
|
+
│ │ ├── ensure-chat-context.ts Chat session creation/retrieval
|
|
34
|
+
│ │ ├── append-chat-section.ts Message persistence with seq numbers
|
|
35
|
+
│ │ └── serv-entry-point.ts Serves deployed app HTML
|
|
36
|
+
│ │
|
|
37
|
+
│ ├── intern/ Internal helpers
|
|
38
|
+
│ │ ├── ensure-slug-binding.ts User/app slug management (random-words)
|
|
39
|
+
│ │ ├── ensure-storage.ts CID calculation (SHA-256 + base58btc)
|
|
40
|
+
│ │ ├── import-map.ts ESM import map generation (esm.sh)
|
|
41
|
+
│ │ ├── render-vibes.tsx HTML rendering with import map injection
|
|
42
|
+
│ │ └── write-apps.ts App record creation with transforms (sucrase, acorn)
|
|
43
|
+
│ │
|
|
44
|
+
│ └── sql/
|
|
45
|
+
│ └── vibes-diy-api-schema.ts Drizzle schema (D1)
|
|
46
|
+
│
|
|
47
|
+
└── tests/ @vibes.diy/api-test
|
|
48
|
+
└── api.test.ts
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Package Summary
|
|
52
|
+
|
|
53
|
+
| Package | Runs On | Purpose |
|
|
54
|
+
| ---------------------- | ------- | --------------------------------------- |
|
|
55
|
+
| `@vibes.diy/api-types` | Both | arktype schemas, request/response types |
|
|
56
|
+
| `@vibes.diy/api-pkg` | Both | Interface + encoders (shared contract) |
|
|
57
|
+
| `@vibes.diy/api-impl` | Client | `VibeDiyApi` WebSocket client class |
|
|
58
|
+
| `@vibes.diy/api-svc` | Server | Cloudflare Worker handlers, D1/Drizzle |
|
|
59
|
+
|
|
60
|
+
## Architecture
|
|
61
|
+
|
|
62
|
+
### Message Envelope
|
|
63
|
+
|
|
64
|
+
All requests are wrapped in a `MsgBase` envelope:
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
interface MsgBase {
|
|
68
|
+
tid: string; // Transaction ID for request/response correlation
|
|
69
|
+
src: string; // Source identifier
|
|
70
|
+
dst: string; // Destination identifier
|
|
71
|
+
ttl: number; // Time-to-live
|
|
72
|
+
payload: unknown; // The actual request/response
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Evento Pipeline
|
|
77
|
+
|
|
78
|
+
The server uses Evento (from `@adviser/cement`) for request routing. Handlers are registered in order:
|
|
79
|
+
|
|
80
|
+
1. **CORS preflight** - Handles OPTIONS requests
|
|
81
|
+
2. **servEntryPoint** - Serves deployed app HTML (hostname routing: `{appSlug}--{userSlug}.{host}/~{fsId}~/`)
|
|
82
|
+
3. **Request logging** - Logs incoming POST/PUT requests, rejects other methods with 503
|
|
83
|
+
4. **ensureAppSlugItem** - App deployment handler
|
|
84
|
+
5. **ensureChatContext** - Chat session handler
|
|
85
|
+
6. **appendChatSection** - Message persistence handler
|
|
86
|
+
7. **Not-found handler** - Returns 501 for unmatched requests (semantically "Not Implemented")
|
|
87
|
+
8. **Error handler** - Catches and formats errors as 500
|
|
88
|
+
|
|
89
|
+
Each handler has `validate` (arktype schema check) and `handle` (business logic) phases. Some handlers also have a `post` phase for cleanup/logging.
|
|
90
|
+
|
|
91
|
+
## Data Flow
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
Client (browser) Server (CF Worker)
|
|
95
|
+
───────────────── ──────────────────
|
|
96
|
+
VibeDiyApi.ensureAppSlug() → cf-serve.ts
|
|
97
|
+
↓ ↓
|
|
98
|
+
WebSocket.send(MsgBox<Req>) → WebSocketPair upgrade
|
|
99
|
+
↓
|
|
100
|
+
CombinedEventoEnDecoder.encode()
|
|
101
|
+
↓
|
|
102
|
+
Evento.trigger() with handlers
|
|
103
|
+
↓
|
|
104
|
+
unwrapMsgBase() → extract payload
|
|
105
|
+
↓
|
|
106
|
+
checkAuth() → verify token
|
|
107
|
+
↓
|
|
108
|
+
handler.handle() → business logic
|
|
109
|
+
↓
|
|
110
|
+
D1 queries (Drizzle ORM)
|
|
111
|
+
↓
|
|
112
|
+
MsgBox<Res> ← SendResponseProvider.send()
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## API Methods
|
|
116
|
+
|
|
117
|
+
### `ensureAppSlug()`
|
|
118
|
+
|
|
119
|
+
Deploy an app with a filesystem. Process:
|
|
120
|
+
|
|
121
|
+
1. Verify auth token (clerk/device-id)
|
|
122
|
+
2. Create or retrieve user slug binding
|
|
123
|
+
3. Create or retrieve app slug binding
|
|
124
|
+
4. Calculate CIDs for all file contents
|
|
125
|
+
5. Store assets in D1 `Assets` table
|
|
126
|
+
6. Apply transforms (jsx-to-js, import map generation)
|
|
127
|
+
7. Create `Apps` record with filesystem manifest
|
|
128
|
+
8. Return `entryPointUrl` for iframe loading
|
|
129
|
+
|
|
130
|
+
### `ensureChatContext()`
|
|
131
|
+
|
|
132
|
+
Create or retrieve a chat session:
|
|
133
|
+
|
|
134
|
+
1. If `contextId` provided, verify it exists and belongs to user
|
|
135
|
+
2. Otherwise, generate new contextId (12-char ID)
|
|
136
|
+
3. Insert into `ChatContexts` table
|
|
137
|
+
4. Return `contextId`
|
|
138
|
+
|
|
139
|
+
### `appendChatSection()`
|
|
140
|
+
|
|
141
|
+
Add messages to a chat context:
|
|
142
|
+
|
|
143
|
+
1. Verify context exists and belongs to user
|
|
144
|
+
2. Get max `seq` for context, increment
|
|
145
|
+
3. Insert into `ChatSections` with `origin` ('user' or 'llm')
|
|
146
|
+
4. Blocks use `BlockMsgs | PromptMsg` types from `@vibes.diy/call-ai-v2`
|
|
147
|
+
5. Return `seq` number
|
|
148
|
+
|
|
149
|
+
## CI/CD
|
|
150
|
+
|
|
151
|
+
The API is bundled into the main vibes.diy Cloudflare Worker (not a separate deployment).
|
|
152
|
+
|
|
153
|
+
### Workflow
|
|
154
|
+
|
|
155
|
+
`.github/workflows/vibes-diy-deploy.yaml`
|
|
156
|
+
|
|
157
|
+
**Triggers:**
|
|
158
|
+
|
|
159
|
+
- Push to `vibes.diy/**/*` paths
|
|
160
|
+
- Tags: `vibes-diy@*`
|
|
161
|
+
- Manual dispatch
|
|
162
|
+
|
|
163
|
+
### Environments
|
|
164
|
+
|
|
165
|
+
| Trigger | Environment | Domain |
|
|
166
|
+
| ----------------------- | ----------- | ------------------------ |
|
|
167
|
+
| Tag `vibes-diy@s*` | staging | `*.dev-v2.vibesdiy.net` |
|
|
168
|
+
| Tag `vibes-diy@p*` | production | `*.prod-v2.vibesdiy.net` |
|
|
169
|
+
| Path push or other tags | dev | `*.dev-v2.vibesdiy.net` |
|
|
170
|
+
|
|
171
|
+
### Deploy Steps
|
|
172
|
+
|
|
173
|
+
Deployment is handled by the GitHub Action (`vibes.diy/actions/deploy`). The action runs:
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
pnpm run build # Build React app + bundle worker
|
|
177
|
+
pnpm run drizzle:d1-remote # Run D1 migrations
|
|
178
|
+
core-cli writeEnv | wrangler secret bulk # Push secrets
|
|
179
|
+
pnpm run deploy:${ENV} # wrangler deploy
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Do not run these manually - push a tag or merge to trigger the workflow.
|
|
183
|
+
|
|
184
|
+
### Infrastructure
|
|
185
|
+
|
|
186
|
+
| Resource | Binding | Purpose |
|
|
187
|
+
| ------------- | -------- | ----------------------------- |
|
|
188
|
+
| D1 Database | `DB` | Chat contexts, sections, apps |
|
|
189
|
+
| Static Assets | `ASSETS` | React app build |
|
|
190
|
+
|
|
191
|
+
### Server Context (VibesApiSQLCtx)
|
|
192
|
+
|
|
193
|
+
All handlers receive a shared context via `ctx.ctx.getOrThrow<VibesApiSQLCtx>("vibesApiCtx")`:
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
interface VibesApiSQLCtx {
|
|
197
|
+
sthis: SuperThis; // Fireproof utilities (logger, nextId, env)
|
|
198
|
+
db: VibesSqlite; // Drizzle DB instance
|
|
199
|
+
tokenApi: Record<string, FPApiToken>; // Auth verifiers by type
|
|
200
|
+
deviceCA: DeviceIdCAIf; // Device ID certificate authority
|
|
201
|
+
logger: Logger; // Structured logger
|
|
202
|
+
params: VibesFPApiParameters; // Service configuration
|
|
203
|
+
cache: CfCacheIf; // Cloudflare cache API
|
|
204
|
+
fetchPkgVersion(pkg): Promise<string | undefined>; // npm registry lookup
|
|
205
|
+
waitUntil<T>(promise): void; // CF worker lifecycle
|
|
206
|
+
ensureStorage(...items): Promise<Result<StorageResult[]>>; // Asset storage
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
### D1 Schema
|
|
211
|
+
|
|
212
|
+
Defined in `svc/sql/vibes-diy-api-schema.ts` using Drizzle ORM.
|
|
213
|
+
|
|
214
|
+
**Assets** - Binary content storage (could move to R2)
|
|
215
|
+
| Column | Type | Description |
|
|
216
|
+
|--------|------|-------------|
|
|
217
|
+
| `assetId` | text PK | CID of content |
|
|
218
|
+
| `content` | blob | Actual content |
|
|
219
|
+
| `created` | text | ISO timestamp |
|
|
220
|
+
|
|
221
|
+
**UserSlugBindings** - Maps users to their human-friendly slugs
|
|
222
|
+
| Column | Type | Description |
|
|
223
|
+
|--------|------|-------------|
|
|
224
|
+
| `userId` | text | User identifier |
|
|
225
|
+
| `userSlug` | text | Human-friendly user slug (unique) |
|
|
226
|
+
| `created` | text | ISO timestamp |
|
|
227
|
+
|
|
228
|
+
Primary key: `(userSlug, userId)`. Unique index on `userSlug`.
|
|
229
|
+
|
|
230
|
+
**AppSlugBindings** - Maps apps to slugs within a user's namespace
|
|
231
|
+
| Column | Type | Description |
|
|
232
|
+
|--------|------|-------------|
|
|
233
|
+
| `userSlug` | text FK | References UserSlugBindings.userSlug |
|
|
234
|
+
| `appSlug` | text | Human-friendly app slug |
|
|
235
|
+
| `created` | text | ISO timestamp |
|
|
236
|
+
|
|
237
|
+
Primary key: `(appSlug, userSlug)`.
|
|
238
|
+
|
|
239
|
+
**Apps** - Deployed app versions with filesystem and environment
|
|
240
|
+
| Column | Type | Description |
|
|
241
|
+
|--------|------|-------------|
|
|
242
|
+
| `appSlug` | text | App identifier |
|
|
243
|
+
| `userId` | text | Owner |
|
|
244
|
+
| `userSlug` | text | Owner's slug |
|
|
245
|
+
| `releaseSeq` | int | Incremented on each deployment |
|
|
246
|
+
| `fsId` | text | CID of filesystem manifest |
|
|
247
|
+
| `env` | json | Environment variables (VibesEnv) |
|
|
248
|
+
| `fileSystem` | json | Array of FileSystemItem with transforms |
|
|
249
|
+
| `mode` | text | 'production' or 'dev' |
|
|
250
|
+
| `created` | text | ISO timestamp |
|
|
251
|
+
|
|
252
|
+
Primary key: `(appSlug, userId, releaseSeq)`. Indexes on `fsId` and `created`.
|
|
253
|
+
|
|
254
|
+
**ChatContexts** - Chat session containers
|
|
255
|
+
| Column | Type | Description |
|
|
256
|
+
|--------|------|-------------|
|
|
257
|
+
| `contextId` | text PK | UUID v4 |
|
|
258
|
+
| `userId` | text | Owner |
|
|
259
|
+
| `created` | text | ISO timestamp |
|
|
260
|
+
|
|
261
|
+
**ChatSections** - Individual messages/blocks within a chat
|
|
262
|
+
| Column | Type | Description |
|
|
263
|
+
|--------|------|-------------|
|
|
264
|
+
| `contextId` | text FK | References ChatContexts.contextId |
|
|
265
|
+
| `seq` | int | Section sequence number (0-indexed, auto-incremented) |
|
|
266
|
+
| `origin` | text | 'user' or 'llm' |
|
|
267
|
+
| `blocks` | json | Array of BlockMsgs or PromptMsg from call-ai-v2 |
|
|
268
|
+
| `created` | text | ISO timestamp |
|
|
269
|
+
|
|
270
|
+
Primary key: `(seq, contextId)`.
|
|
271
|
+
|
|
272
|
+
### Environment Variables
|
|
273
|
+
|
|
274
|
+
**Required:**
|
|
275
|
+
| Variable | Purpose |
|
|
276
|
+
|----------|---------|
|
|
277
|
+
| `CLOUD_SESSION_TOKEN_PUBLIC` | Public key for cloud session tokens |
|
|
278
|
+
| `CLERK_PUBLISHABLE_KEY` | Clerk auth verification |
|
|
279
|
+
| `DEVICE_ID_CA_PRIV_KEY` | Device ID certificate authority private key |
|
|
280
|
+
| `DEVICE_ID_CA_CERT` | Device ID certificate authority cert |
|
|
281
|
+
| `FP_VERSION` | Fireproof version for import maps |
|
|
282
|
+
| `VIBES_SVC_HOSTNAME_BASE` | Base hostname for deployed apps (e.g., `vibes.app`) |
|
|
283
|
+
|
|
284
|
+
**Optional (with defaults):**
|
|
285
|
+
| Variable | Default | Purpose |
|
|
286
|
+
|----------|---------|---------|
|
|
287
|
+
| `VIBES_SVC_PROTOCOL` | `https` | Protocol for deployed apps |
|
|
288
|
+
| `MAX_APP_SLUG_PER_USER_ID` | `10` | Max app slugs per user |
|
|
289
|
+
| `MAX_USER_SLUG_PER_USER_ID` | `10` | Max user slugs per user |
|
|
290
|
+
| `MAX_APPS_PER_USER_ID` | `50` | Max app deployments per user |
|
|
291
|
+
|
|
292
|
+
## Message Types
|
|
293
|
+
|
|
294
|
+
### VibeFile (for deployment)
|
|
295
|
+
|
|
296
|
+
Six variants for different content types:
|
|
297
|
+
|
|
298
|
+
| Type | Content | Use Case |
|
|
299
|
+
| ------------------- | ------------------------------------ | ------------------------------ |
|
|
300
|
+
| `code-block` | Inline string, `lang: 'jsx' \| 'js'` | JSX/JS source code |
|
|
301
|
+
| `code-ref` | `refId` reference | Code stored elsewhere |
|
|
302
|
+
| `str-asset-block` | Inline string | CSS, JSON, text files |
|
|
303
|
+
| `str-asset-ref` | `refId` reference | String assets stored elsewhere |
|
|
304
|
+
| `uint8-asset-block` | `Uint8Array` | Images, fonts, binaries |
|
|
305
|
+
| `uint8-asset-ref` | `refId` reference | Binary assets stored elsewhere |
|
|
306
|
+
|
|
307
|
+
All file types share base properties:
|
|
308
|
+
|
|
309
|
+
```typescript
|
|
310
|
+
{
|
|
311
|
+
filename: string; // Must start with /, no //, /../, /./
|
|
312
|
+
entryPoint?: boolean; // Last one wins, marks app entry
|
|
313
|
+
mimetype?: string; // Derived from filename if not set
|
|
314
|
+
}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
### FileSystemItem (stored result)
|
|
318
|
+
|
|
319
|
+
After processing, files become `FileSystemItem`:
|
|
320
|
+
|
|
321
|
+
```typescript
|
|
322
|
+
{
|
|
323
|
+
fileName: string;
|
|
324
|
+
mimeType: string;
|
|
325
|
+
assetId: string; // CID of content
|
|
326
|
+
assetURI: string; // sql://Assets.assetId, s3://..., r2://...
|
|
327
|
+
entryPoint?: boolean;
|
|
328
|
+
size: number;
|
|
329
|
+
transform?: {
|
|
330
|
+
type: 'jsx-to-js' | 'imports' | 'import-map' | 'transformed';
|
|
331
|
+
// ... transform-specific fields
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
### Auth Types
|
|
337
|
+
|
|
338
|
+
```typescript
|
|
339
|
+
type DashAuthType = {
|
|
340
|
+
type: "clerk" | "device-id";
|
|
341
|
+
token: string;
|
|
342
|
+
};
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
Auth is verified via `tokenApi` which supports:
|
|
346
|
+
|
|
347
|
+
- **clerk** - Clerk JWT verification using `CLERK_PUB_JWT_KEY` / `CLERK_PUB_JWT_URL` env vars
|
|
348
|
+
- **device-id** - Device certificate verification using `DEVICE_ID_CA_*` keys
|
|
349
|
+
|
|
350
|
+
## Client Usage
|
|
351
|
+
|
|
352
|
+
> [!WARNING]
|
|
353
|
+
> The client (`@vibes.diy/api-impl`) is currently a work-in-progress. While it can send requests over WebSocket, the response correlation logic (matching server responses to requests via `tid`) is not yet fully implemented. It is currently primarily used for testing with direct handler calls.
|
|
354
|
+
|
|
355
|
+
The client is currently used in tests. The main vibes.diy app doesn't use it yet - integration is in progress.
|
|
356
|
+
|
|
357
|
+
### Creating a Client
|
|
358
|
+
|
|
359
|
+
```typescript
|
|
360
|
+
import { VibeDiyApi } from "@vibes.diy/api-impl";
|
|
361
|
+
import { Result } from "@adviser/cement";
|
|
362
|
+
|
|
363
|
+
const api = new VibeDiyApi({
|
|
364
|
+
apiUrl: "wss://api.vibes.diy/v1/ws", // Default if omitted
|
|
365
|
+
getToken: async () => {
|
|
366
|
+
// Return auth token (Clerk or device-id)
|
|
367
|
+
return Result.Ok({ type: "clerk", token: clerkToken });
|
|
368
|
+
},
|
|
369
|
+
timeoutMs: 10000, // Default: 10s request timeout
|
|
370
|
+
});
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
The client uses `KeyedResolvOnce` for connection pooling - multiple `VibeDiyApi` instances with the same `apiUrl` share a WebSocket connection. (See `impl/index.ts` for custom message routing options via the `msg` config.)
|
|
374
|
+
|
|
375
|
+
### Deploying an App
|
|
376
|
+
|
|
377
|
+
```typescript
|
|
378
|
+
const res = await api.ensureAppSlug({
|
|
379
|
+
mode: "dev", // 'dev' or 'production'
|
|
380
|
+
appSlug: "my-app", // optional, server generates 3-word slug
|
|
381
|
+
userSlug: "my-user", // optional, server generates 3-word slug
|
|
382
|
+
env: { API_KEY: "..." }, // optional, passed to app runtime
|
|
383
|
+
fileSystem: [
|
|
384
|
+
{
|
|
385
|
+
type: "code-block",
|
|
386
|
+
lang: "jsx",
|
|
387
|
+
filename: "/App.jsx", // Must start with /, becomes entry point
|
|
388
|
+
entryPoint: true,
|
|
389
|
+
content: "export default function App() { return <div>Hello</div>; }",
|
|
390
|
+
},
|
|
391
|
+
],
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
if (res.isOk()) {
|
|
395
|
+
const { entryPointUrl, fsId, userSlug, appSlug, fileSystem } = res.Ok();
|
|
396
|
+
// entryPointUrl -> https://{appSlug}--{userSlug}.{hostnameBase}/~{fsId}~/
|
|
397
|
+
// e.g. https://my-app--my-user.vibes.app/~zABC123~/
|
|
398
|
+
// fsId -> CID of filesystem manifest
|
|
399
|
+
// fileSystem -> Array<FileSystemItem> with assetIds and transforms
|
|
400
|
+
}
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
**Response includes:**
|
|
404
|
+
|
|
405
|
+
- `entryPointUrl` - URL to load in iframe (constructed from `VIBES_SVC_*` config)
|
|
406
|
+
- `wrapperUrl` - URL for wrapper page with auth handoff
|
|
407
|
+
- `fsId` - CID of the filesystem manifest
|
|
408
|
+
- `fileSystem` - Processed `FileSystemItem[]` with CIDs and transforms applied
|
|
409
|
+
|
|
410
|
+
### Chat Context Management
|
|
411
|
+
|
|
412
|
+
```typescript
|
|
413
|
+
// Create a new chat context (server generates contextId)
|
|
414
|
+
const ctx = await api.ensureChatContext({});
|
|
415
|
+
|
|
416
|
+
// Or retrieve/create with a specific contextId
|
|
417
|
+
const ctx = await api.ensureChatContext({ contextId: "my-context-id" });
|
|
418
|
+
|
|
419
|
+
if (ctx.isOk()) {
|
|
420
|
+
const { contextId } = ctx.Ok();
|
|
421
|
+
|
|
422
|
+
// Append a user message
|
|
423
|
+
const userRes = await api.appendChatSection({
|
|
424
|
+
contextId,
|
|
425
|
+
origin: "user", // 'user' | 'llm'
|
|
426
|
+
blocks: [
|
|
427
|
+
// BlockMsgs or PromptMsg from @vibes.diy/call-ai-v2
|
|
428
|
+
{
|
|
429
|
+
type: "prompt.txt",
|
|
430
|
+
streamId: "stream-1",
|
|
431
|
+
request: { model: "gpt-4", messages: [{ role: "user", content: "Hello" }] },
|
|
432
|
+
timestamp: new Date(),
|
|
433
|
+
},
|
|
434
|
+
],
|
|
435
|
+
});
|
|
436
|
+
// userRes.Ok().seq -> 0 (first section)
|
|
437
|
+
|
|
438
|
+
// Append LLM response
|
|
439
|
+
const llmRes = await api.appendChatSection({
|
|
440
|
+
contextId,
|
|
441
|
+
origin: "llm",
|
|
442
|
+
blocks: sectionBlocks, // BlockMsgs from call-ai sections stream
|
|
443
|
+
});
|
|
444
|
+
// llmRes.Ok().seq -> 1 (second section)
|
|
445
|
+
}
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
**Note:** Context ownership is enforced - you can only append to contexts created by your userId.
|
|
449
|
+
|
|
450
|
+
### Testing
|
|
451
|
+
|
|
452
|
+
Tests use a local handler directly rather than WebSocket. See `api/tests/api.test.ts` for the full setup including:
|
|
453
|
+
|
|
454
|
+
- Creating a local D1/libsql database
|
|
455
|
+
- Setting up test device-id auth
|
|
456
|
+
- Calling the handler directly
|
|
457
|
+
|
|
458
|
+
Note: The test passes an ad-hoc `fetch` property via TypeScript structural typing, but this isn't part of the official `VibeDiyApiParam` interface. A proper `fetch` override may be added in the future.
|
|
459
|
+
|
|
460
|
+
## Running Tests
|
|
461
|
+
|
|
462
|
+
```bash
|
|
463
|
+
cd vibes.diy/api/tests
|
|
464
|
+
pnpm test
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
## Implementation Details
|
|
468
|
+
|
|
469
|
+
### URL Structure
|
|
470
|
+
|
|
471
|
+
Deployed apps are served via hostname-based routing:
|
|
472
|
+
|
|
473
|
+
```
|
|
474
|
+
https://{appSlug}--{userSlug}.{hostnameBase}/~{fsId}~/
|
|
475
|
+
└────────────────────┘ └──────────┘ └──────┘
|
|
476
|
+
hostname base domain version path
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
Example: `https://my-app--fuzzy-purple-elephant.vibes.app/~z4PhNX7vuL~/`
|
|
480
|
+
|
|
481
|
+
The `extractHostToBindings()` function parses:
|
|
482
|
+
|
|
483
|
+
- Hostname pattern: `{appSlug}--{userSlug}.{rest}`
|
|
484
|
+
- Path pattern: `/~{fsId}~/` (fsId starts with `z`, 8+ chars)
|
|
485
|
+
- If no fsId in path, serves latest production release
|
|
486
|
+
|
|
487
|
+
### Slug Generation
|
|
488
|
+
|
|
489
|
+
When `appSlug` or `userSlug` are not provided, the server generates 3-word slugs using the `random-words` package:
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
generate({ exactly: 1, wordsPerString: 3, separator: "-" });
|
|
493
|
+
// → "fuzzy-purple-elephant"
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
Up to 5 attempts are made to find a unique slug before failing.
|
|
497
|
+
|
|
498
|
+
### Transform Pipeline
|
|
499
|
+
|
|
500
|
+
The `write-apps.ts` module applies transforms to uploaded files:
|
|
501
|
+
|
|
502
|
+
1. **JSX → JS** (`sucrase` with automatic JSX runtime)
|
|
503
|
+
- Input: `code-block` with `lang: "jsx"`
|
|
504
|
+
- Output: `/~~transformed~~/{cid}` with `transform: { type: "transformed", action: "jsx-to-js" }`
|
|
505
|
+
|
|
506
|
+
2. **Import Extraction** (`acorn` parser)
|
|
507
|
+
- Parses all JS files for `import`/`export` statements
|
|
508
|
+
- Extracts bare specifiers (e.g., `react`, `@fireproof/core`)
|
|
509
|
+
|
|
510
|
+
3. **Import Map Generation**
|
|
511
|
+
- Unknown packages → npm registry lookup for version → `esm.sh` URL
|
|
512
|
+
- Predefined mappings for React 19.2.1, Fireproof, Clerk, etc.
|
|
513
|
+
- Output: `/~~calculated~~/import-map.json` with `transform: { type: "import-map" }`
|
|
514
|
+
|
|
515
|
+
### fsId Calculation
|
|
516
|
+
|
|
517
|
+
The `fsId` is a deterministic CID computed from:
|
|
518
|
+
|
|
519
|
+
```typescript
|
|
520
|
+
hash(sortedFilenames + mimetypes + contentCIDs + sortedEnvJSON);
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
Same files + same env = same fsId (enables deduplication).
|
|
524
|
+
|
|
525
|
+
### Asset Caching
|
|
526
|
+
|
|
527
|
+
`serv-entry-point.ts` uses two-tier Cloudflare caching:
|
|
528
|
+
|
|
529
|
+
1. **Global cache** by CID: `assetCacheUrl/{assetId}`
|
|
530
|
+
2. **Path cache** by request URL
|
|
531
|
+
|
|
532
|
+
On cache miss: D1 query → populate both caches via `waitUntil()`.
|
|
533
|
+
|
|
534
|
+
### App Eviction
|
|
535
|
+
|
|
536
|
+
When a user exceeds `MAX_APPS_PER_USER_ID`:
|
|
537
|
+
|
|
538
|
+
- Oldest `dev` mode apps are evicted first (10% of total + 1)
|
|
539
|
+
- `production` apps are preserved
|
package/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vibes.diy/api-queue",
|
|
3
|
+
"version": "0.0.0-smoke-70d942c5-1774564519",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"build": "core-cli tsc && wrangler build",
|
|
7
|
+
"dev": "wrangler dev",
|
|
8
|
+
"deploy": "wrangler deploy",
|
|
9
|
+
"deploy:dev": "wrangler deploy --env dev",
|
|
10
|
+
"deploy:prod": "wrangler deploy --env prod"
|
|
11
|
+
},
|
|
12
|
+
"dependencies": {
|
|
13
|
+
"@adviser/cement": "~0.5.34",
|
|
14
|
+
"@cloudflare/puppeteer": "~1.0.6",
|
|
15
|
+
"@fireproof/core-runtime": "~0.24.13",
|
|
16
|
+
"@vibes.diy/api-svc": "0.0.0-smoke-70d942c5-1774564519",
|
|
17
|
+
"@vibes.diy/api-types": "0.0.0-smoke-70d942c5-1774564519",
|
|
18
|
+
"arktype": "~2.2.0",
|
|
19
|
+
"drizzle-orm": "~0.45.1"
|
|
20
|
+
},
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/VibesDIY/vibes.diy.git"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import puppeteer from "@cloudflare/puppeteer";
|
|
2
|
+
import { isEvtNewFsId, isMsgBase, msgBase } from "@vibes.diy/api-types";
|
|
3
|
+
import { R2ToS3Api, storeScreenshot } from "@vibes.diy/api-svc";
|
|
4
|
+
import { cfDrizzle } from "@vibes.diy/api-svc/cf-serve.js";
|
|
5
|
+
import { createVibesApiTables } from "@vibes.diy/api-svc/sql/tables.js";
|
|
6
|
+
import { type } from "arktype";
|
|
7
|
+
import { ensureSuperThis } from "@fireproof/core-runtime";
|
|
8
|
+
import { LoggerImpl } from "@adviser/cement";
|
|
9
|
+
export async function takeScreenshot(event, env) {
|
|
10
|
+
console.log(`Taking screenshot for ${event.vibeUrl} (fsId: ${event.fsId})`);
|
|
11
|
+
const browser = await puppeteer.launch(env.BROWSER);
|
|
12
|
+
try {
|
|
13
|
+
const page = await browser.newPage();
|
|
14
|
+
await page.setViewport({
|
|
15
|
+
width: 1280,
|
|
16
|
+
height: 720,
|
|
17
|
+
deviceScaleFactor: 1,
|
|
18
|
+
});
|
|
19
|
+
await page.goto(event.vibeUrl, {
|
|
20
|
+
waitUntil: "networkidle0",
|
|
21
|
+
timeout: 30000,
|
|
22
|
+
});
|
|
23
|
+
const screenshot = await page.screenshot({
|
|
24
|
+
type: "jpeg",
|
|
25
|
+
quality: 85,
|
|
26
|
+
fullPage: false,
|
|
27
|
+
});
|
|
28
|
+
return screenshot;
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
await browser.close();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export async function processScreenShotEvent(message, env) {
|
|
35
|
+
if (!isMsgBase(message)) {
|
|
36
|
+
const x = msgBase(message);
|
|
37
|
+
if (x instanceof type.errors) {
|
|
38
|
+
console.error("Received message that is not MsgBase but matches MsgBase structure:", x.summary, message);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
console.error("Received message that is not MsgBase:", message);
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const payload = message.payload;
|
|
46
|
+
if (isEvtNewFsId(payload)) {
|
|
47
|
+
console.log("Processing ScreenShotEvent:", {
|
|
48
|
+
shotUrl: payload.vibeUrl,
|
|
49
|
+
fsId: payload.fsId,
|
|
50
|
+
});
|
|
51
|
+
const screenshot = await takeScreenshot(payload, env);
|
|
52
|
+
const screenshotData = new Uint8Array(screenshot);
|
|
53
|
+
console.log(`Screenshot taken for ${payload.fsId}: ${screenshotData.byteLength} bytes`);
|
|
54
|
+
const { db } = await cfDrizzle(env);
|
|
55
|
+
const sthis = ensureSuperThis({ logger: new LoggerImpl() });
|
|
56
|
+
const tables = createVibesApiTables(env.DB_FLAVOUR ?? "sqlite");
|
|
57
|
+
const result = await storeScreenshot({
|
|
58
|
+
sql: { dbFlavour: env.DB_FLAVOUR ?? "sqlite", db, tables },
|
|
59
|
+
s3Api: new R2ToS3Api(env.FS_IDS_BUCKET, sthis),
|
|
60
|
+
}, payload.fsId, screenshotData);
|
|
61
|
+
if (result.isErr()) {
|
|
62
|
+
console.error(`Failed to store screenshot: ${result.Err()}`);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
console.log(`Screenshot stored with assetId: ${result.Ok().assetUrl}`);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
console.error("Received message with unrecognized payload:", payload);
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=screen-shotter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"screen-shotter.js","sourceRoot":"","sources":["../jsr/screen-shotter.ts"],"names":[],"mappings":"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"}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": [
|
|
3
|
+
"/Users/menabe/Software/fproof/vibes.diy-main/tsconfig.dist.json"
|
|
4
|
+
],
|
|
5
|
+
"compilerOptions": {
|
|
6
|
+
"outDir": "../npm/",
|
|
7
|
+
"sourceMap": true,
|
|
8
|
+
"noEmit": false
|
|
9
|
+
},
|
|
10
|
+
"include": [
|
|
11
|
+
"**/*"
|
|
12
|
+
],
|
|
13
|
+
"exclude": [
|
|
14
|
+
"node_modules",
|
|
15
|
+
"dist",
|
|
16
|
+
".git",
|
|
17
|
+
".vscode"
|
|
18
|
+
]
|
|
19
|
+
}
|
package/worker.d.ts
ADDED
package/worker.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { processScreenShotEvent } from "./screen-shotter.js";
|
|
2
|
+
export default {
|
|
3
|
+
async queue(batch, env) {
|
|
4
|
+
for (const message of batch.messages) {
|
|
5
|
+
try {
|
|
6
|
+
console.log("Queue message received:", message.id, typeof message.body);
|
|
7
|
+
let body = message.body;
|
|
8
|
+
if (typeof message.body === "string") {
|
|
9
|
+
body = JSON.parse(message.body);
|
|
10
|
+
console.log("Message body:", body);
|
|
11
|
+
}
|
|
12
|
+
await processScreenShotEvent(body, env);
|
|
13
|
+
message.ack();
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
console.error("Failed to process queue message:", error);
|
|
17
|
+
message.retry();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=worker.js.map
|
package/worker.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.js","sourceRoot":"","sources":["../jsr/worker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,eAAe;IACb,KAAK,CAAC,KAAK,CAAC,KAAmB,EAAE,GAAU;QACzC,KAAK,MAAM,OAAO,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YACrC,IAAI,CAAC;gBACH,OAAO,CAAC,GAAG,CAAC,yBAAyB,EAAE,OAAO,CAAC,EAAE,EAAE,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;gBACxE,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;gBACxB,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;oBACrC,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAc,CAAC,CAAC;oBAC1C,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;gBACrC,CAAC;gBACD,MAAM,sBAAsB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;gBACxC,OAAO,CAAC,GAAG,EAAE,CAAC;YAChB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,KAAK,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;gBACzD,OAAO,CAAC,KAAK,EAAE,CAAC;YAClB,CAAC;QACH,CAAC;IACH,CAAC;CAC+B,CAAC"}
|
package/wrangler.toml
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
name = "vibes-diy-v2-queue-consumer"
|
|
2
|
+
main = "./worker.ts"
|
|
3
|
+
compatibility_date = "2025-02-24"
|
|
4
|
+
compatibility_flags = ["nodejs_compat"]
|
|
5
|
+
|
|
6
|
+
[browser]
|
|
7
|
+
binding = "BROWSER"
|
|
8
|
+
|
|
9
|
+
[[d1_databases]]
|
|
10
|
+
binding = "DB"
|
|
11
|
+
database_name = "dev-vibes-diy-v2"
|
|
12
|
+
database_id = "105530de-9900-435b-92f4-15347af604f6"
|
|
13
|
+
|
|
14
|
+
[[r2_buckets]]
|
|
15
|
+
binding = "FS_IDS_BUCKET"
|
|
16
|
+
bucket_name = "vibes-diy-fs-ids"
|
|
17
|
+
|
|
18
|
+
[[queues.consumers]]
|
|
19
|
+
queue = "vibes-service"
|
|
20
|
+
max_batch_size = 10
|
|
21
|
+
max_batch_timeout = 30
|
|
22
|
+
|
|
23
|
+
[env.dev]
|
|
24
|
+
name = "vibes-diy-v2-queue-consumer-dev"
|
|
25
|
+
|
|
26
|
+
[env.dev.browser]
|
|
27
|
+
binding = "BROWSER"
|
|
28
|
+
|
|
29
|
+
[[env.dev.d1_databases]]
|
|
30
|
+
binding = "DB"
|
|
31
|
+
database_name = "dev-vibes-diy-v2"
|
|
32
|
+
database_id = "105530de-9900-435b-92f4-15347af604f6"
|
|
33
|
+
|
|
34
|
+
[[env.dev.r2_buckets]]
|
|
35
|
+
binding = "FS_IDS_BUCKET"
|
|
36
|
+
bucket_name = "vibes-diy-fs-ids"
|
|
37
|
+
|
|
38
|
+
[[env.dev.queues.consumers]]
|
|
39
|
+
queue = "vibes-service-dev"
|
|
40
|
+
max_batch_size = 10
|
|
41
|
+
max_batch_timeout = 30
|
|
42
|
+
|
|
43
|
+
[env.prod]
|
|
44
|
+
name = "vibes-diy-v2-queue-consumer-prod"
|
|
45
|
+
|
|
46
|
+
[env.prod.browser]
|
|
47
|
+
binding = "BROWSER"
|
|
48
|
+
|
|
49
|
+
[[env.prod.d1_databases]]
|
|
50
|
+
binding = "DB"
|
|
51
|
+
database_name = "prod-vibes-diy-v2"
|
|
52
|
+
database_id = "0f783eae-91cf-49c4-a706-6e4d2498cb4a"
|
|
53
|
+
|
|
54
|
+
[[env.prod.r2_buckets]]
|
|
55
|
+
binding = "FS_IDS_BUCKET"
|
|
56
|
+
bucket_name = "vibes-diy-fs-ids"
|
|
57
|
+
|
|
58
|
+
[[env.prod.queues.consumers]]
|
|
59
|
+
queue = "vibes-service-prod"
|
|
60
|
+
max_batch_size = 10
|
|
61
|
+
max_batch_timeout = 30
|