id.org.ai 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAuBvB;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,QAAQ;IACvB,0CAA0C;IAC1C,GAAG,EAAE,MAAM,CAAA;IACX,yCAAyC;IACzC,KAAK,EAAE,gCAAgC,CAAA;IACvC,mDAAmD;IACnD,SAAS,EAAE,MAAM,CAAA;IACjB,wDAAwD;IACxD,SAAS,EAAE,MAAM,CAAA;CAClB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;EAKzB,CAAA;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,QAAQ,CAExD;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAAC,KAAK,CAAC,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,CAQjE;AAID;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,WAAW,IAAK,SAAQ,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC;IACnD,kDAAkD;IAClD,KAAK,EAAE,4BAA4B,CAAA;IACnC,wDAAwD;IACxD,KAAK,EAAE,MAAM,CAAA;IACb,0BAA0B;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,4DAA4D;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAClC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAA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;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,OAAO,CAEtD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,WAAW,CAAC,GAAG;IAC9D,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,GACA,OAAO,CAYT;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAE1D"}
package/dist/index.js ADDED
@@ -0,0 +1,555 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * @module id.org.ai
4
+ *
5
+ * Identity primitives for schema.org.ai
6
+ *
7
+ * This package provides identity types for humans and AI agents:
8
+ * - {@link Identity} - Base identity interface
9
+ * - {@link User} - Human user identity
10
+ * - {@link AgentIdentity} - AI agent identity
11
+ * - {@link Credential} - Authentication credentials
12
+ * - {@link Session} - Active sessions
13
+ *
14
+ * All types follow JSON-LD conventions with `$id` and `$type` fields.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { createUser, isUser, UserSchema } from 'id.org.ai'
19
+ *
20
+ * const user = createUser({
21
+ * email: 'alice@example.com',
22
+ * name: 'Alice'
23
+ * })
24
+ *
25
+ * // Runtime validation
26
+ * if (isUser(unknownData)) {
27
+ * console.log(unknownData.email)
28
+ * }
29
+ *
30
+ * // Schema validation
31
+ * const result = UserSchema.safeParse(data)
32
+ * ```
33
+ *
34
+ * @version 0.1.0
35
+ */
36
+ import { z } from 'zod';
37
+ // === Internal Helpers ===
38
+ /**
39
+ * Generates a unique identifier URI for a given resource type
40
+ * @internal
41
+ */
42
+ function generateId(prefix) {
43
+ const uuid = crypto.randomUUID();
44
+ return `https://schema.org.ai/${prefix}/${uuid}`;
45
+ }
46
+ /**
47
+ * Generates a secure random token for session authentication
48
+ * @internal
49
+ */
50
+ function generateToken() {
51
+ return crypto.randomUUID().replace(/-/g, '') + crypto.randomUUID().replace(/-/g, '');
52
+ }
53
+ /**
54
+ * Zod schema for validating Identity objects
55
+ *
56
+ * Use this schema for runtime validation of identity data.
57
+ *
58
+ * @see {@link Identity}
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const result = IdentitySchema.safeParse(unknownData)
63
+ * if (result.success) {
64
+ * console.log(result.data.$id)
65
+ * } else {
66
+ * console.error(result.error)
67
+ * }
68
+ * ```
69
+ */
70
+ export const IdentitySchema = z.object({
71
+ $id: z.string(),
72
+ $type: z.literal('https://schema.org.ai/Identity'),
73
+ createdAt: z.string(),
74
+ updatedAt: z.string(),
75
+ });
76
+ /**
77
+ * Type guard to check if an object is a valid Identity
78
+ *
79
+ * Uses Zod schema validation internally to ensure type safety.
80
+ *
81
+ * @param obj - Object to validate
82
+ * @returns True if the object is a valid Identity
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const data: unknown = fetchFromAPI()
87
+ * if (isIdentity(data)) {
88
+ * // TypeScript knows data is Identity
89
+ * console.log(data.createdAt)
90
+ * }
91
+ * ```
92
+ */
93
+ export function isIdentity(obj) {
94
+ return IdentitySchema.safeParse(obj).success;
95
+ }
96
+ /**
97
+ * Factory function to create a new Identity
98
+ *
99
+ * Creates a complete Identity object with auto-generated `$id` (if not provided)
100
+ * and timestamps. The `$type` is always set to the correct JSON-LD type.
101
+ *
102
+ * @param input - Optional partial identity data
103
+ * @param input.$id - Custom identifier URI (auto-generated if not provided)
104
+ * @returns A complete Identity object with all required fields
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * // Auto-generate all fields
109
+ * const identity = createIdentity()
110
+ *
111
+ * // With custom $id
112
+ * const identity = createIdentity({ $id: 'https://example.com/id/custom' })
113
+ * ```
114
+ */
115
+ export function createIdentity(input) {
116
+ const now = new Date().toISOString();
117
+ return {
118
+ $id: input?.$id ?? generateId('identities'),
119
+ $type: 'https://schema.org.ai/Identity',
120
+ createdAt: now,
121
+ updatedAt: now,
122
+ };
123
+ }
124
+ /**
125
+ * Zod schema for validating User objects
126
+ *
127
+ * Validates all User fields including email format validation.
128
+ *
129
+ * @see {@link User}
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * const result = UserSchema.safeParse({
134
+ * $id: 'https://example.com/users/1',
135
+ * $type: 'https://schema.org.ai/User',
136
+ * email: 'alice@example.com',
137
+ * name: 'Alice',
138
+ * createdAt: new Date().toISOString(),
139
+ * updatedAt: new Date().toISOString()
140
+ * })
141
+ *
142
+ * if (!result.success) {
143
+ * console.error('Invalid email:', result.error.issues)
144
+ * }
145
+ * ```
146
+ */
147
+ export const UserSchema = z.object({
148
+ $id: z.string(),
149
+ $type: z.literal('https://schema.org.ai/User'),
150
+ email: z.string().email(),
151
+ name: z.string(),
152
+ profile: z.record(z.unknown()).optional(),
153
+ createdAt: z.string(),
154
+ updatedAt: z.string(),
155
+ });
156
+ /**
157
+ * Type guard to check if an object is a valid User
158
+ *
159
+ * Uses Zod schema validation internally including email format validation.
160
+ *
161
+ * @param obj - Object to validate
162
+ * @returns True if the object is a valid User
163
+ *
164
+ * @example
165
+ * ```typescript
166
+ * const data: unknown = await fetchUser(id)
167
+ * if (isUser(data)) {
168
+ * // TypeScript knows data is User
169
+ * sendEmail(data.email, `Hello ${data.name}!`)
170
+ * }
171
+ * ```
172
+ */
173
+ export function isUser(obj) {
174
+ return UserSchema.safeParse(obj).success;
175
+ }
176
+ /**
177
+ * Factory function to create a new User
178
+ *
179
+ * Creates a complete User object with auto-generated `$id` (if not provided),
180
+ * timestamps, and the correct `$type`. Email and name are required.
181
+ *
182
+ * @param input - User data (email and name required)
183
+ * @param input.email - User's email address
184
+ * @param input.name - User's display name
185
+ * @param input.$id - Custom identifier URI (auto-generated if not provided)
186
+ * @param input.profile - Optional profile metadata
187
+ * @returns A complete User object ready for storage
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * // Basic user creation
192
+ * const user = createUser({
193
+ * email: 'alice@example.com',
194
+ * name: 'Alice Smith'
195
+ * })
196
+ *
197
+ * // With profile data
198
+ * const user = createUser({
199
+ * email: 'bob@example.com',
200
+ * name: 'Bob Jones',
201
+ * profile: {
202
+ * avatar: 'https://example.com/bob.png',
203
+ * bio: 'Software developer',
204
+ * settings: { theme: 'dark' }
205
+ * }
206
+ * })
207
+ *
208
+ * // With custom $id
209
+ * const user = createUser({
210
+ * $id: 'https://myapp.com/users/alice',
211
+ * email: 'alice@example.com',
212
+ * name: 'Alice'
213
+ * })
214
+ * ```
215
+ */
216
+ export function createUser(input) {
217
+ const now = new Date().toISOString();
218
+ return {
219
+ $id: input.$id ?? generateId('users'),
220
+ $type: 'https://schema.org.ai/User',
221
+ email: input.email,
222
+ name: input.name,
223
+ profile: input.profile,
224
+ createdAt: now,
225
+ updatedAt: now,
226
+ };
227
+ }
228
+ /**
229
+ * Zod schema for validating AgentIdentity objects
230
+ *
231
+ * Validates all AgentIdentity fields including model, capabilities array,
232
+ * and autonomous flag.
233
+ *
234
+ * @see {@link AgentIdentity}
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * const result = AgentIdentitySchema.safeParse(agentData)
239
+ * if (result.success) {
240
+ * const agent = result.data
241
+ * if (agent.autonomous) {
242
+ * console.log('Agent can act independently')
243
+ * }
244
+ * }
245
+ * ```
246
+ */
247
+ export const AgentIdentitySchema = z.object({
248
+ $id: z.string(),
249
+ $type: z.literal('https://schema.org.ai/AgentIdentity'),
250
+ model: z.string(),
251
+ capabilities: z.array(z.string()),
252
+ autonomous: z.boolean(),
253
+ createdAt: z.string(),
254
+ updatedAt: z.string(),
255
+ });
256
+ /**
257
+ * Type guard to check if an object is a valid AgentIdentity
258
+ *
259
+ * Uses Zod schema validation internally to ensure type safety.
260
+ *
261
+ * @param obj - Object to validate
262
+ * @returns True if the object is a valid AgentIdentity
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * const identity: unknown = getIdentity(id)
267
+ * if (isAgentIdentity(identity)) {
268
+ * // TypeScript knows identity is AgentIdentity
269
+ * console.log(`Agent model: ${identity.model}`)
270
+ * console.log(`Capabilities: ${identity.capabilities.join(', ')}`)
271
+ * }
272
+ * ```
273
+ */
274
+ export function isAgentIdentity(obj) {
275
+ return AgentIdentitySchema.safeParse(obj).success;
276
+ }
277
+ /**
278
+ * Factory function to create a new AgentIdentity
279
+ *
280
+ * Creates a complete AgentIdentity object with auto-generated `$id` (if not provided),
281
+ * timestamps, and the correct `$type`. Model, capabilities, and autonomous flag are required.
282
+ *
283
+ * @param input - Agent identity data
284
+ * @param input.model - The AI model name (e.g., 'claude-3-opus')
285
+ * @param input.capabilities - Array of capability strings
286
+ * @param input.autonomous - Whether the agent can act autonomously
287
+ * @param input.$id - Custom identifier URI (auto-generated if not provided)
288
+ * @returns A complete AgentIdentity object ready for storage
289
+ *
290
+ * @example
291
+ * ```typescript
292
+ * // Create a supervised agent
293
+ * const assistant = createAgentIdentity({
294
+ * model: 'claude-3-opus',
295
+ * capabilities: ['text-generation', 'code-analysis'],
296
+ * autonomous: false
297
+ * })
298
+ *
299
+ * // Create an autonomous agent
300
+ * const worker = createAgentIdentity({
301
+ * model: 'claude-3-haiku',
302
+ * capabilities: ['task-execution', 'tool-use'],
303
+ * autonomous: true
304
+ * })
305
+ *
306
+ * // With custom $id
307
+ * const namedAgent = createAgentIdentity({
308
+ * $id: 'https://myapp.com/agents/ralph',
309
+ * model: 'claude-3-opus',
310
+ * capabilities: ['coding', 'review'],
311
+ * autonomous: true
312
+ * })
313
+ * ```
314
+ */
315
+ export function createAgentIdentity(input) {
316
+ const now = new Date().toISOString();
317
+ return {
318
+ $id: input.$id ?? generateId('agents'),
319
+ $type: 'https://schema.org.ai/AgentIdentity',
320
+ model: input.model,
321
+ capabilities: input.capabilities,
322
+ autonomous: input.autonomous,
323
+ createdAt: now,
324
+ updatedAt: now,
325
+ };
326
+ }
327
+ /**
328
+ * Zod schema for validating Credential objects
329
+ *
330
+ * Validates credential type as one of the allowed enum values.
331
+ *
332
+ * @see {@link Credential}
333
+ * @see {@link CredentialType}
334
+ *
335
+ * @example
336
+ * ```typescript
337
+ * const result = CredentialSchema.safeParse(credentialData)
338
+ * if (result.success) {
339
+ * const cred = result.data
340
+ * if (cred.credentialType === 'oauth' && cred.provider) {
341
+ * console.log(`OAuth via ${cred.provider}`)
342
+ * }
343
+ * }
344
+ * ```
345
+ */
346
+ export const CredentialSchema = z.object({
347
+ $id: z.string(),
348
+ $type: z.literal('https://schema.org.ai/Credential'),
349
+ identityId: z.string(),
350
+ credentialType: z.enum(['password', 'oauth', 'api_key', 'sso']),
351
+ provider: z.string().optional(),
352
+ expiresAt: z.string().optional(),
353
+ });
354
+ /**
355
+ * Type guard to check if an object is a valid Credential
356
+ *
357
+ * Uses Zod schema validation internally to ensure type safety.
358
+ *
359
+ * @param obj - Object to validate
360
+ * @returns True if the object is a valid Credential
361
+ *
362
+ * @example
363
+ * ```typescript
364
+ * const data: unknown = await getCredential(id)
365
+ * if (isCredential(data)) {
366
+ * // TypeScript knows data is Credential
367
+ * console.log(`Credential type: ${data.credentialType}`)
368
+ * if (data.expiresAt) {
369
+ * console.log(`Expires: ${data.expiresAt}`)
370
+ * }
371
+ * }
372
+ * ```
373
+ */
374
+ export function isCredential(obj) {
375
+ return CredentialSchema.safeParse(obj).success;
376
+ }
377
+ /**
378
+ * Factory function to create a new Credential
379
+ *
380
+ * Creates a complete Credential object with auto-generated `$id` (if not provided)
381
+ * and the correct `$type`. The identityId and credentialType are required.
382
+ *
383
+ * @param input - Credential data
384
+ * @param input.identityId - Reference to the owning identity
385
+ * @param input.credentialType - Type of credential (password, oauth, api_key, sso)
386
+ * @param input.$id - Custom identifier URI (auto-generated if not provided)
387
+ * @param input.provider - OAuth/SSO provider name (optional)
388
+ * @param input.expiresAt - Expiration timestamp (optional)
389
+ * @returns A complete Credential object ready for storage
390
+ *
391
+ * @example
392
+ * ```typescript
393
+ * // Password credential (never expires)
394
+ * const passwordCred = createCredential({
395
+ * identityId: 'https://schema.org.ai/users/123',
396
+ * credentialType: 'password'
397
+ * })
398
+ *
399
+ * // OAuth credential with expiration
400
+ * const oauthCred = createCredential({
401
+ * identityId: 'https://schema.org.ai/users/123',
402
+ * credentialType: 'oauth',
403
+ * provider: 'google',
404
+ * expiresAt: '2024-12-31T23:59:59Z'
405
+ * })
406
+ *
407
+ * // API key for programmatic access
408
+ * const apiKeyCred = createCredential({
409
+ * identityId: 'https://schema.org.ai/agents/worker-1',
410
+ * credentialType: 'api_key'
411
+ * })
412
+ * ```
413
+ */
414
+ export function createCredential(input) {
415
+ return {
416
+ $id: input.$id ?? generateId('credentials'),
417
+ $type: 'https://schema.org.ai/Credential',
418
+ identityId: input.identityId,
419
+ credentialType: input.credentialType,
420
+ provider: input.provider,
421
+ expiresAt: input.expiresAt,
422
+ };
423
+ }
424
+ /**
425
+ * Zod schema for validating Session objects
426
+ *
427
+ * Validates all Session fields including non-empty token requirement.
428
+ *
429
+ * @see {@link Session}
430
+ *
431
+ * @example
432
+ * ```typescript
433
+ * const result = SessionSchema.safeParse(sessionData)
434
+ * if (result.success) {
435
+ * const session = result.data
436
+ * // Use the validated session
437
+ * } else {
438
+ * console.error('Invalid session:', result.error.issues)
439
+ * }
440
+ * ```
441
+ */
442
+ export const SessionSchema = z.object({
443
+ $id: z.string(),
444
+ $type: z.literal('https://schema.org.ai/Session'),
445
+ identityId: z.string(),
446
+ token: z.string().min(1),
447
+ expiresAt: z.string(),
448
+ metadata: z.record(z.unknown()).optional(),
449
+ });
450
+ /**
451
+ * Type guard to check if an object is a valid Session
452
+ *
453
+ * Uses Zod schema validation internally to ensure type safety.
454
+ * Note: This only validates structure, not expiration. Use {@link isSessionExpired}
455
+ * to check if a session has expired.
456
+ *
457
+ * @param obj - Object to validate
458
+ * @returns True if the object is a valid Session
459
+ *
460
+ * @example
461
+ * ```typescript
462
+ * const data: unknown = await getSession(token)
463
+ * if (isSession(data)) {
464
+ * // TypeScript knows data is Session
465
+ * if (!isSessionExpired(data)) {
466
+ * console.log(`Session valid until: ${data.expiresAt}`)
467
+ * }
468
+ * }
469
+ * ```
470
+ */
471
+ export function isSession(obj) {
472
+ return SessionSchema.safeParse(obj).success;
473
+ }
474
+ /**
475
+ * Factory function to create a new Session
476
+ *
477
+ * Creates a complete Session object with auto-generated `$id`, `token`, and
478
+ * `expiresAt` (24 hours from now) if not provided. Only `identityId` is required.
479
+ *
480
+ * @param input - Session data
481
+ * @param input.identityId - Reference to the authenticated identity
482
+ * @param input.$id - Custom identifier URI (auto-generated if not provided)
483
+ * @param input.token - Custom session token (auto-generated if not provided)
484
+ * @param input.expiresAt - Custom expiration (defaults to 24 hours from now)
485
+ * @param input.metadata - Optional session metadata
486
+ * @returns A complete Session object ready for storage
487
+ *
488
+ * @example
489
+ * ```typescript
490
+ * // Basic session with defaults (24h expiry, auto-generated token)
491
+ * const session = createSession({
492
+ * identityId: 'https://schema.org.ai/users/123'
493
+ * })
494
+ *
495
+ * // Session with custom expiration
496
+ * const shortSession = createSession({
497
+ * identityId: 'https://schema.org.ai/users/123',
498
+ * expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString() // 1 hour
499
+ * })
500
+ *
501
+ * // Session with metadata
502
+ * const trackedSession = createSession({
503
+ * identityId: 'https://schema.org.ai/users/123',
504
+ * metadata: {
505
+ * userAgent: 'Mozilla/5.0...',
506
+ * ip: '192.168.1.1',
507
+ * device: 'desktop'
508
+ * }
509
+ * })
510
+ * ```
511
+ */
512
+ export function createSession(input) {
513
+ // Default expiration: 24 hours from now
514
+ const defaultExpiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
515
+ return {
516
+ $id: input.$id ?? generateId('sessions'),
517
+ $type: 'https://schema.org.ai/Session',
518
+ identityId: input.identityId,
519
+ token: input.token ?? generateToken(),
520
+ expiresAt: input.expiresAt ?? defaultExpiresAt,
521
+ metadata: input.metadata,
522
+ };
523
+ }
524
+ /**
525
+ * Check if a session has expired
526
+ *
527
+ * Compares the session's `expiresAt` timestamp against the current time.
528
+ *
529
+ * @param session - The session to check
530
+ * @returns True if the session has expired (expiresAt is in the past)
531
+ *
532
+ * @example
533
+ * ```typescript
534
+ * const session = await getSession(token)
535
+ * if (isSession(session)) {
536
+ * if (isSessionExpired(session)) {
537
+ * // Redirect to login
538
+ * throw new Error('Session expired')
539
+ * }
540
+ * // Continue with authenticated request
541
+ * }
542
+ * ```
543
+ *
544
+ * @example
545
+ * ```typescript
546
+ * // Clean up expired sessions
547
+ * const sessions = await getAllSessions()
548
+ * const activeSessions = sessions.filter(s => !isSessionExpired(s))
549
+ * const expiredSessions = sessions.filter(isSessionExpired)
550
+ * ```
551
+ */
552
+ export function isSessionExpired(session) {
553
+ return new Date(session.expiresAt).getTime() < Date.now();
554
+ }
555
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,2BAA2B;AAE3B;;;GAGG;AACH,SAAS,UAAU,CAAC,MAAc;IAChC,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,EAAE,CAAA;IAChC,OAAO,yBAAyB,MAAM,IAAI,IAAI,EAAE,CAAA;AAClD,CAAC;AAED;;;GAGG;AACH,SAAS,aAAa;IACpB,OAAO,MAAM,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAA;AACtF,CAAC;AAiCD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAC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AAK,CAAC,QAAQ;KACzB,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgB;IAC/C,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;AAC3D,CAAC"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "id.org.ai",
3
+ "version": "0.1.0",
4
+ "description": "Identity primitives for AI systems following schema.org.ai conventions",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "test": "vitest run",
17
+ "test:watch": "vitest"
18
+ },
19
+ "dependencies": {
20
+ "zod": "^3.22.0"
21
+ },
22
+ "devDependencies": {
23
+ "typescript": "^5.3.0",
24
+ "vitest": "^1.0.0"
25
+ },
26
+ "keywords": [
27
+ "identity",
28
+ "authentication",
29
+ "schema.org.ai",
30
+ "json-ld",
31
+ "ai"
32
+ ],
33
+ "license": "MIT"
34
+ }