enigmatic 0.33.0 → 0.35.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.
@@ -1,310 +0,0 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
-
4
- // Load client.js and custom.js into jsdom
5
- const clientCode = fs.readFileSync(path.join(__dirname, '../public/client.js'), 'utf8')
6
- const customCode = fs.readFileSync(path.join(__dirname, '../public/custom.js'), 'utf8')
7
-
8
- describe('client.js', () => {
9
- beforeEach(() => {
10
- // Reset DOM
11
- global.document.body.innerHTML = ''
12
- global.document.head.innerHTML = ''
13
-
14
- // Clear window.custom
15
- global.window.custom = {}
16
-
17
- // Execute custom.js first (defines window.custom)
18
- eval(customCode)
19
- // Execute client.js code
20
- eval(clientCode)
21
- })
22
-
23
- describe('$ and $$ selectors', () => {
24
- test('$ selects single element', () => {
25
- global.document.body.innerHTML = '<div id="test">Hello</div>'
26
- expect(window.$('#test').textContent).toBe('Hello')
27
- })
28
-
29
- test('$$ selects multiple elements', () => {
30
- global.document.body.innerHTML = '<div class="item">1</div><div class="item">2</div>'
31
- const items = window.$$('.item')
32
- expect(items.length).toBe(2)
33
- expect(items[0].textContent).toBe('1')
34
- expect(items[1].textContent).toBe('2')
35
- })
36
-
37
- test('$ returns null for non-existent element', () => {
38
- global.document.body.innerHTML = '<div>Test</div>'
39
- expect(window.$('#nonexistent')).toBeNull()
40
- })
41
-
42
- test('$$ returns empty NodeList for non-existent elements', () => {
43
- global.document.body.innerHTML = '<div>Test</div>'
44
- expect(window.$$('.nonexistent').length).toBe(0)
45
- })
46
- })
47
-
48
- describe('window API functions', () => {
49
- let originalFetch
50
- let originalLocation
51
-
52
- beforeEach(() => {
53
- originalFetch = global.fetch
54
- global.fetch = jest.fn()
55
- originalLocation = global.window.location
56
- delete global.window.location
57
- global.window.location = { href: '' }
58
- })
59
-
60
- afterEach(() => {
61
- global.fetch = originalFetch
62
- global.window.location = originalLocation
63
- })
64
-
65
- test('window.get makes GET request with encoded key', async () => {
66
- global.fetch.mockResolvedValueOnce({
67
- ok: true,
68
- json: () => Promise.resolve({ value: 'test' })
69
- })
70
-
71
- const result = await window.get('test key')
72
-
73
- expect(global.fetch).toHaveBeenCalledWith(
74
- `${window.api_url}/test%20key`
75
- )
76
- expect(result).toEqual({ value: 'test' })
77
- })
78
-
79
- test('window.set makes POST request with string value', async () => {
80
- global.fetch.mockResolvedValueOnce({
81
- ok: true,
82
- json: () => Promise.resolve({ status: 'saved' })
83
- })
84
-
85
- const result = await window.set('test', 'value')
86
-
87
- expect(global.fetch).toHaveBeenCalledWith(
88
- `${window.api_url}/test`,
89
- expect.objectContaining({
90
- method: 'POST',
91
- body: 'value'
92
- })
93
- )
94
- expect(result).toEqual({ status: 'saved' })
95
- })
96
-
97
- test('window.set stringifies object values', async () => {
98
- global.fetch.mockResolvedValueOnce({
99
- ok: true,
100
- json: () => Promise.resolve({ status: 'saved' })
101
- })
102
-
103
- await window.set('test', { key: 'value' })
104
-
105
- expect(global.fetch).toHaveBeenCalledWith(
106
- `${window.api_url}/test`,
107
- expect.objectContaining({
108
- method: 'POST',
109
- body: JSON.stringify({ key: 'value' })
110
- })
111
- )
112
- })
113
-
114
- test('window.delete makes DELETE request', async () => {
115
- global.fetch.mockResolvedValueOnce({
116
- ok: true,
117
- json: () => Promise.resolve({ status: 'deleted' })
118
- })
119
-
120
- const result = await window.delete('test')
121
-
122
- expect(global.fetch).toHaveBeenCalledWith(
123
- `${window.api_url}/test`,
124
- expect.objectContaining({
125
- method: 'DELETE'
126
- })
127
- )
128
- expect(result).toEqual({ status: 'deleted' })
129
- })
130
-
131
- test('window.put makes PUT request with string body', async () => {
132
- global.fetch.mockResolvedValueOnce({
133
- ok: true,
134
- json: () => Promise.resolve({ status: 'saved' })
135
- })
136
-
137
- const result = await window.put('test', 'content')
138
-
139
- expect(global.fetch).toHaveBeenCalledWith(
140
- `${window.api_url}/test`,
141
- expect.objectContaining({
142
- method: 'PUT',
143
- body: 'content'
144
- })
145
- )
146
- expect(result).toEqual({ status: 'saved' })
147
- })
148
-
149
- test('window.put stringifies object body', async () => {
150
- global.fetch.mockResolvedValueOnce({
151
- ok: true,
152
- json: () => Promise.resolve({ status: 'saved' })
153
- })
154
-
155
- await window.put('test', { data: 'value' })
156
-
157
- expect(global.fetch).toHaveBeenCalledWith(
158
- `${window.api_url}/test`,
159
- expect.objectContaining({
160
- method: 'PUT',
161
- body: JSON.stringify({ data: 'value' })
162
- })
163
- )
164
- })
165
-
166
- test('window.put handles Blob body', async () => {
167
- const blob = new Blob(['test'], { type: 'text/plain' })
168
- global.fetch.mockResolvedValueOnce({
169
- ok: true,
170
- json: () => Promise.resolve({ status: 'saved' })
171
- })
172
-
173
- await window.put('test', blob)
174
-
175
- expect(global.fetch).toHaveBeenCalledWith(
176
- `${window.api_url}/test`,
177
- expect.objectContaining({
178
- method: 'PUT',
179
- body: blob
180
- })
181
- )
182
- })
183
-
184
- test('window.purge makes PURGE request', async () => {
185
- global.fetch.mockResolvedValueOnce({
186
- ok: true,
187
- json: () => Promise.resolve({ status: 'deleted' })
188
- })
189
-
190
- const result = await window.purge('test')
191
-
192
- expect(global.fetch).toHaveBeenCalledWith(
193
- `${window.api_url}/test`,
194
- expect.objectContaining({
195
- method: 'PURGE'
196
- })
197
- )
198
- expect(result).toEqual({ status: 'deleted' })
199
- })
200
-
201
- test('window.list makes PROPFIND request to base URL', async () => {
202
- global.fetch.mockResolvedValueOnce({
203
- ok: true,
204
- json: () => Promise.resolve([{ name: 'file1' }])
205
- })
206
-
207
- const result = await window.list()
208
-
209
- expect(global.fetch).toHaveBeenCalledWith(
210
- window.api_url,
211
- expect.objectContaining({
212
- method: 'PROPFIND'
213
- })
214
- )
215
- expect(result).toEqual([{ name: 'file1' }])
216
- })
217
-
218
- test('window.login redirects to /login', () => {
219
- window.login()
220
- expect(global.window.location.href).toBe(`${window.api_url}/login`)
221
- })
222
-
223
- test('window.logout redirects to /logout', () => {
224
- window.logout()
225
- expect(global.window.location.href).toBe(`${window.api_url}/logout`)
226
- })
227
- })
228
-
229
- describe('window.custom components', () => {
230
- test('hello-world component is a function', () => {
231
- expect(typeof window.custom['hello-world']).toBe('function')
232
- })
233
-
234
- test('hello-world component renders correctly', () => {
235
- const result = window.custom['hello-world']('Test')
236
- expect(result).toBe('Hello Test')
237
- })
238
-
239
- test('hello-world-2 component has prop and render methods', () => {
240
- expect(window.custom['hello-world-2']).toBeDefined()
241
- expect(typeof window.custom['hello-world-2'].prop).toBe('function')
242
- expect(typeof window.custom['hello-world-2'].render).toBe('function')
243
- })
244
-
245
- test('hello-world-2 component prop works', () => {
246
- const result = window.custom['hello-world-2'].prop('Test')
247
- expect(result).toBe('Test World')
248
- })
249
-
250
- test('hello-world-2 component render works', () => {
251
- const result = window.custom['hello-world-2'].render('Test')
252
- expect(result).toBe('Test World')
253
- })
254
- })
255
-
256
-
257
- describe('window.state proxy', () => {
258
- test('state.set updates DOM elements with data attribute', () => {
259
- global.document.body.innerHTML = '<hello-world data="name"></hello-world>'
260
-
261
- window.state.name = 'John'
262
-
263
- const el = global.document.querySelector('hello-world')
264
- expect(el.innerHTML).toBe('Hello John')
265
- })
266
-
267
- test('state.set updates multiple elements with same data attribute', () => {
268
- global.document.body.innerHTML = '<hello-world data="name"></hello-world><hello-world data="name"></hello-world>'
269
-
270
- window.state.name = 'Jane'
271
-
272
- const els = global.document.querySelectorAll('hello-world')
273
- expect(els[0].innerHTML).toBe('Hello Jane')
274
- expect(els[1].innerHTML).toBe('Hello Jane')
275
- })
276
-
277
- test('state.set works with object components', () => {
278
- global.document.body.innerHTML = '<hello-world-2 data="test"></hello-world-2>'
279
-
280
- window.state.test = 'Hello'
281
-
282
- const el = global.document.querySelector('hello-world-2')
283
- expect(el.innerHTML).toBe('Hello World')
284
- })
285
-
286
- test('state.set stores value in proxy object', () => {
287
- window.state.test = 'value'
288
- expect(window.state.test).toBe('value')
289
- })
290
-
291
- test('state.set handles multiple properties', () => {
292
- global.document.body.innerHTML = '<hello-world data="a"></hello-world><hello-world data="b"></hello-world>'
293
-
294
- window.state.a = 'A'
295
- window.state.b = 'B'
296
-
297
- expect(global.document.querySelector('[data="a"]').innerHTML).toBe('Hello A')
298
- expect(global.document.querySelector('[data="b"]').innerHTML).toBe('Hello B')
299
- })
300
-
301
- test('state.set does not update elements without matching data attribute', () => {
302
- global.document.body.innerHTML = '<hello-world data="name"></hello-world><div data="other">Original</div>'
303
-
304
- window.state.name = 'John'
305
-
306
- expect(global.document.querySelector('[data="name"]').innerHTML).toBe('Hello John')
307
- expect(global.document.querySelector('[data="other"]').innerHTML).toBe('Original')
308
- })
309
- })
310
- })
@@ -1,7 +0,0 @@
1
- module.exports = {
2
- testEnvironment: 'jsdom',
3
- testMatch: ['**/__tests__/**/*.test.js'],
4
- setupFilesAfterEnv: ['<rootDir>/__tests__/jest.setup.js'],
5
- testTimeout: 10000,
6
- rootDir: require('path').resolve(__dirname, '..')
7
- }
@@ -1,9 +0,0 @@
1
- // Mock window.components if not defined
2
- if (typeof window !== 'undefined' && !window.components) {
3
- window.components = {}
4
- }
5
-
6
- // Add fetch polyfill for jsdom
7
- if (typeof global.fetch === 'undefined') {
8
- global.fetch = require('whatwg-fetch').fetch
9
- }
package/bun-server.js DELETED
@@ -1,130 +0,0 @@
1
- import { S3Client } from "bun";
2
-
3
- const dbPath = "db.json";
4
- const db = await Bun.file(dbPath).json().catch(() => ({}));
5
- const s3 = new S3Client({
6
- accessKeyId: Bun.env.CLOUDFLARE_ACCESS_KEY_ID,
7
- secretAccessKey: Bun.env.CLOUDFLARE_SECRET_ACCESS_KEY,
8
- bucket: Bun.env.CLOUDFLARE_BUCKET_NAME,
9
- endpoint: Bun.env.CLOUDFLARE_PUBLIC_URL
10
- });
11
- const json = (data, status = 200, extraHeaders = {}) => new Response(JSON.stringify(data), {
12
- status,
13
- headers: {
14
- "Access-Control-Allow-Origin": "*",
15
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PURGE, PROPFIND, DOWNLOAD, OPTIONS",
16
- "Access-Control-Allow-Headers": "Content-Type, Authorization, Cookie, X-HTTP-Method-Override",
17
- "Access-Control-Allow-Credentials": "true",
18
- "Content-Type": "application/json",
19
- ...extraHeaders
20
- }
21
- });
22
- const writeDb = () => Bun.write(dbPath, JSON.stringify(db, null, 2));
23
- const redirect = (url, cookie = null) => new Response(null, {
24
- status: 302,
25
- headers: { Location: url, ...(cookie && { "Set-Cookie": cookie }) }
26
- });
27
-
28
- export default {
29
- async fetch(req) {
30
- console.log('req.method', req.method);
31
- const url = new URL(req.url);
32
- const key = url.pathname.slice(1);
33
- const cb = `${url.origin}/callback`;
34
- const token = req.headers.get("Cookie")?.match(/token=([^;]+)/)?.[1];
35
- const user = token ? db[`session:${token}`] : null;
36
-
37
- if (req.method === "OPTIONS") return json(null, 204);
38
-
39
- if (url.pathname === '/login') {
40
- return Response.redirect(`https://${Bun.env.AUTH0_DOMAIN}/authorize?${new URLSearchParams({
41
- response_type: "code",
42
- client_id: Bun.env.AUTH0_CLIENT_ID,
43
- redirect_uri: cb,
44
- scope: "openid email profile"
45
- })}`);
46
- }
47
-
48
- if (url.pathname === '/callback') {
49
- const code = url.searchParams.get("code");
50
- if (!code) return json({ error: 'No code' }, 400);
51
- const tRes = await fetch(`https://${Bun.env.AUTH0_DOMAIN}/oauth/token`, {
52
- method: "POST",
53
- headers: { "content-type": "application/json" },
54
- body: JSON.stringify({
55
- grant_type: "authorization_code",
56
- client_id: Bun.env.AUTH0_CLIENT_ID,
57
- client_secret: Bun.env.AUTH0_CLIENT_SECRET,
58
- code,
59
- redirect_uri: cb
60
- })
61
- });
62
- if (!tRes.ok) return json({ error: 'Auth error' }, 401);
63
- const tokens = await tRes.json();
64
- const userInfo = await (await fetch(`https://${Bun.env.AUTH0_DOMAIN}/userinfo`, {
65
- headers: { Authorization: `Bearer ${tokens.access_token}` }
66
- })).json();
67
- const session = crypto.randomUUID();
68
- db[`session:${session}`] = {
69
- ...userInfo,
70
- login_time: new Date().toISOString(),
71
- access_token_expires_at: tokens.expires_in ? new Date(Date.now() + tokens.expires_in * 1000).toISOString() : null
72
- };
73
- await writeDb();
74
- return redirect(url.origin, `token=${session}; HttpOnly; Path=/; Secure; SameSite=Lax; Max-Age=86400`);
75
- }
76
-
77
- if (!token || !user) return json({ error: 'Unauthorized' }, 401);
78
-
79
- if (url.pathname === '/logout') {
80
- delete db[`session:${token}`];
81
- await writeDb();
82
- return redirect(url.origin, "token=; Max-Age=0; Path=/");
83
- }
84
-
85
- const files = { '/': 'index.html', '/client.js': 'client.js', '/custom.js': 'custom.js' };
86
- if (req.method === 'GET' && files[url.pathname]) return new Response(Bun.file(`./public/${files[url.pathname]}`));
87
-
88
- console.log(req.method);
89
- switch (req.method) {
90
- case 'GET': return json(db[key]);
91
- case 'POST':
92
- const value = await req.text();
93
- db[key] = (() => { try { return JSON.parse(value); } catch { return value; } })();
94
- await writeDb();
95
- return json({ key, value });
96
- case 'DELETE':
97
- delete db[key];
98
- await writeDb();
99
- return json({ status: "Deleted" });
100
- case 'PUT':
101
- await s3.write(`${user.sub}/${key}`, req.body);
102
- return json({ status: "Saved to R2" });
103
- case 'PURGE':
104
- await s3.delete(`${user.sub}/${key}`);
105
- return json({ status: "Deleted from R2" });
106
- case 'PROPFIND':
107
- const list = await s3.list({ prefix: `${user.sub}/` });
108
- const items = Array.isArray(list) ? list : (list?.contents || []);
109
- return json(items.map(item => ({
110
- name: item.key?.split('/').pop() || item.name || item.Key,
111
- lastModified: item.lastModified || item.LastModified,
112
- size: item.size || item.Size || 0
113
- })));
114
- case 'PATCH':
115
- try {
116
- const exists = await s3.exists(`${user.sub}/${key}`);
117
- if (!exists) return json({ error: 'File not found' }, 404);
118
- const file = await s3.file(`${user.sub}/${key}`);
119
- if (!file) return json({ error: 'File not found' }, 404);
120
- return new Response(file.stream(), { headers: file.headers });
121
- } catch (err) {
122
- console.error('Download error:', err);
123
- return json({ error: 'File not found', details: err.message }, 404);
124
- }
125
- default: return json({ error: 'Method not allowed' }, 405);
126
- }
127
- },
128
- port: 3000,
129
- tls: { cert: Bun.file("cert.pem"), key: Bun.file("key.pem") }
130
- };